如何从 pymongo 聚合中获取结果计数?
How to get the count of result from a pymongo aggregate?
我正在尝试获取 pymongo aggregate
方法的结果计数。 aggregate
方法 returns 一个 command_cursor
对象,但根据 pymongo docs 只有 cursor
对象有一个 count()
方法。如何在不使用任何循环的情况下获取 aggregate
函数结果的计数?
我认为你应该return从你的聚合中计算:
pipeline = [
{"$match": YOURQUERY},
{"$group": {"_id": groupby, "count": {"$sum":1}}}, # this returns count
{YOUR_PIPELINES}
]
cursor = db.collection.aggregate(pipeline)
你可以这样做:
result = list(db.collection.aggregate([...]))
print(len(result))
我正在尝试获取 pymongo aggregate
方法的结果计数。 aggregate
方法 returns 一个 command_cursor
对象,但根据 pymongo docs 只有 cursor
对象有一个 count()
方法。如何在不使用任何循环的情况下获取 aggregate
函数结果的计数?
我认为你应该return从你的聚合中计算:
pipeline = [
{"$match": YOURQUERY},
{"$group": {"_id": groupby, "count": {"$sum":1}}}, # this returns count
{YOUR_PIPELINES}
]
cursor = db.collection.aggregate(pipeline)
你可以这样做:
result = list(db.collection.aggregate([...]))
print(len(result))