【问题标题】:How to get the count of result from a pymongo aggregate?如何从 pymongo 聚合中获取结果计数?
【发布时间】:2020-06-25 04:34:06
【问题描述】:

我正在尝试获取 pymongo aggregate 方法的结果计数。 aggregate 方法返回一个command_cursor 对象,但根据pymongo docs,只有cursor 对象有一个count() 方法。如何在不使用任何循环的情况下获取 aggregate 函数的结果计数?

【问题讨论】:

    标签: python pymongo aws-documentdb


    【解决方案1】:

    我认为您应该从聚合中返回计数:

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

    【讨论】:

    • 这不是为每个返回的结果添加一个count 字段吗?
    • 这是对具有某些标准的文档组的计数。您可以通过对文档进行分组来计数,然后将此计数传递给管道的下一个阶段。
    • 要么是这个答案,要么就是这样做:len(list(cursor))
    • @ScamCast 这正是我想要的。我不想在查询中添加$group 管道,所以我需要使用python 完成一些事情。请将其添加为答案。
    【解决方案2】:

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-13
      • 2020-07-18
      • 2021-07-01
      • 2021-12-06
      • 2021-07-26
      • 1970-01-01
      • 2015-11-07
      • 2016-04-08
      相关资源
      最近更新 更多