Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count results from mongo aggregate method

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?

like image 829
rafalmag Avatar asked Jul 03 '26 02:07

rafalmag


1 Answers

Ok. I found 2 different similar stackoverflow questions:

  • MongoDB - Aggregation Framework (Total Count)

  • Mongo aggregation cursor & counting

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

like image 161
rafalmag Avatar answered Jul 04 '26 16:07

rafalmag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!