How to count pymongo aggregation cursor without iterating

jadhavmahendra7 picture jadhavmahendra7 · Nov 26, 2015 · Viewed 7.6k times · Source

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?

Answer

chridam picture chridam · Nov 26, 2015

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))