count of result in aggregate

24 views
Skip to first unread message

Ali hallaji

unread,
May 31, 2014, 5:59:11 AM5/31/14
to mongod...@googlegroups.com
Hi,
how to count all result in aggregate?

Victor Hooi

unread,
Jun 16, 2014, 2:37:20 AM6/16/14
to mongod...@googlegroups.com
Hi Ali,

You can count items in an aggregation using the $group aggregation operator and $sum.

For example, if we have the following documents:

> db.dogs.find()
{ "_id" : ObjectId("539e8c759a349385717251f0"), "name" : "spot" } { "_id" : ObjectId("539e8c759a349385717251f1"), "name" : "fifo" } { "_id" : ObjectId("539e8c759a349385717251f2"), "name" : "spot the second" }


Here is a how to do a simple tally of all documents in this collection:

> db.dogs.aggregate({$group: {_id: "dogs", "count":
{"$sum": 1}
}});
{ "_id" : "dogs", "count" : 3 }


You can put this in a pipeline this with your other aggregation operations. I'd encourage you to read through the aggregation examples on the Zip Code Data Set and User Preference Data. If you get stuck, paste the code you have for your aggregation and somebody can help you debug it.

Please let me know if you have any queries about any of the above.

Regards,
Victor
Reply all
Reply to author
Forward
0 new messages