3

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?

rafalmag
  • 1,791
  • 1
  • 17
  • 24
  • If the items would not contain duplicates, we could use find query like: db.orders.find({"customer" : "Bob","items":"pear"}).count() to get the result without using aggregation... – rafalmag Sep 18 '14 at 19:30
  • Well yes that is true. So the question is do you just want to count the documents that match your condition or do you want to count the occurrences of that condition where there are duplicates? This is the essential difference in the two forms. – Neil Lunn Sep 19 '14 at 01:39
  • @NeilLunn Forget about the example. I just want to count returned documents from aggregate method. – rafalmag Sep 19 '14 at 09:06

1 Answers1

3

Ok. I found 2 different similar stackoverflow questions:

and it looks this is not possible to count the results without mentioned grouping.

Community
  • 1
  • 1
rafalmag
  • 1,791
  • 1
  • 17
  • 24