【问题标题】:Get the size of the result of aggregate method MongoDB获取聚合方法MongoDB结果的大小
【发布时间】:2018-12-21 08:10:57
【问题描述】:

我有这个聚合查询:

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() 方法那样更快地获取聚合查询结果的数量的方法?

谢谢

【问题讨论】:

    标签: python-3.x mongodb aggregate pymongo-3.x


    【解决方案1】:

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

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

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

    【讨论】:

    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多