Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count pymongo aggregation cursor without iterating

I want to get the total number of records in an aggregate cursor in pymongo version 3.0+. Is there any way to get total count without iterating over the cursor?

cursor = db.collection.aggregate([{"$match": options},{"$group": {"_id": groupby,"count": {"$sum":1}}} ])
cursorlist = [c for c in cursor]
print len(cursorlist)

Is there any way to skip the above iteration?

like image 639
jadhavmahendra7 Avatar asked Nov 26 '15 07:11

jadhavmahendra7


People also ask

How do you count the cursor objects in Python?

count() Counts the number of documents referenced by a cursor. Append the count() method to a find() query to return the number of matching documents.

How can I tell if Pymongo cursor is empty?

Check if the Cursor object is empty or not? Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well.


1 Answers

You could add another group pipeline where you specify an _id value of None to calculate accumulated values for all the input documents as a whole, this is where you can get the total count, as well as the original grouped counts, albeit in an accumulated array:

>>> pipeline = [
...     {"$match": options},
...     {"$group": {"_id": groupby, "count": {"$sum":1}}},
...     {"$group": {"_id": None, "total": {"$sum": 1}, "details":{"$push":{"groupby": "$_id", "count": "$count"}}}}
... ]
>>> list(db.collection.aggregate(pipeline))
like image 85
chridam Avatar answered Sep 29 '22 19:09

chridam