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?
您可以添加另一个组管道,您可以在其中指定_id
值None
来计算所有输入文档的累计值,这是您可以从中获取总计数以及原始分组计数的地方,尽管它是一个累积数组:
>>> 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))
链接地址: http://www.djcxy.com/p/88946.html
上一篇: 无法在现有文件上挂载卷,文件存在