How to count pymongo aggregation cursor without iteration

I want to get the total number of records in an aggregated cursor in pymongo version 3.0+. Is there a way to get the total without repeating 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 a way to skip the above iteration?

+7
python mongodb
source share
1 answer

You can add another group pipeline in which you specify the value _id None to calculate the accumulated values ​​for all input documents as a whole, here you can get the total score, as well as the original group is considered, although in the 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)) 
+4
source share

All Articles