获取聚合方法结果的大小MongoDB

Get the size of the result of aggregate method MongoDB

我有这个聚合查询:

cr = db.last_response.aggregate([

{"$unwind": '$blocks'},
{"$match": {"sender_id": "1234", "page_id": "563921", "blocks.tag": "pay1"}},
{"$project": {"block": "$blocks.block"}}
])

现在我想得到它返回的元素的数量(是否为空游标)。

我是这样做的: 我定义了一个空数组:

x = []

我遍历游标并追加数组 x:

for i in cr :
   x.append(i['block'])
print("length of the result of aggregation cursor :",len(x))

我的问题是:有没有像 find() 查询的 count() 方法那样更快地获取聚合查询结果数的方法?

谢谢

更快的方法是拒绝将所有数据从 mongod 传输到您的应用程序的操作。为此,您可以将最后的小组赛阶段添加到 count docs

{"$group": {"_id": None, "count": {"$sum": 1}}},

这意味着 mongod 会聚合并作为文档的结果计数。 如果不执行聚合管道,则无法获取结果计数。