How to count results from mongo shell aggregate method?
Is there a simpler way than adding
{$group:{_id:null,count:{$sum:1}}}
to the query?
For example I have following schema:
{
"_id" : ObjectId("541b2b6813e401118fcf9ec6"),
"customer" : "Bob",
"items" : [
"pear",
"apple"
]
}
And I want to count how many pears has Bob ordered (he had multiple orders, and items can contain duplicates). I came with following query:
db.orders.aggregate(
[
{
$match: {
"customer": {
$eq: "Bob"
}
}
},
{
"$unwind": "$items"
},
{
$match: {
"items": {
$eq: "pear"
}
}
},
{
$group: {
_id: null,
count: {
$sum: 1
}
}
}
]
)
With response:
{ "_id" : null, "count" : 1 }
Is there a simpler way?