简体   繁体   English

如何从pymongo聚合中获取结果计数?

[英]How to get the count of result from a pymongo aggregate?

I am trying to get the result count of a pymongo aggregate method.我正在尝试获取 pymongo aggregate方法的结果计数。 The aggregate method returns a command_cursor object but according to the pymongo docs only the cursor object has a count() method. aggregate方法返回一个command_cursor对象,但根据pymongo 文档,只有cursor对象具有count()方法。 How do I get the count of the result of an aggregate function without using any kind of loop?如何在不使用任何类型的循环的情况下获取aggregate函数的结果计数?

I think you should return count from your aggregation:我认为您应该从聚合中返回计数:

pipeline = [
     {"$match": YOURQUERY},
     {"$group": {"_id": groupby, "count": {"$sum":1}}}, # this returns count
     {YOUR_PIPELINES}
]
cursor = db.collection.aggregate(pipeline)

You can do:你可以做:

result = list(db.collection.aggregate([...]))
print(len(result))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM