【问题标题】:Aggregate - count records with pymongo聚合 - 使用 pymongo 计算记录
【发布时间】:2017-09-05 11:23:47
【问题描述】:

我想用 pymongo 计算匹配记录。 我查阅了文档:https://docs.mongodb.com/manual/reference/operator/aggregation/group/#group-by-month-day-and-year

我知道我应该这样做:

db.foo_baz.aggregate([{'$group': {'_id': '$baz_id', 'count': {'$sum': 1}}}])

但是,我收到此错误:

      File "/usr/lib/python3.6/site-packages/mongomock/collection.py", line 1531, in aggregate
    from_field = key.replace('$', '')
AttributeError: 'int' object has no attribute 'replace'

添加评论

我认为 pymongo 会将其评估为以下 mongodb 语句:

 db.foo_baz.aggregate({{$group: {_id: '$baz_id', count: {$sum: 1}}}])

从 mongodb 控制台运行时,这给了我预期的结果,在我的例子中是:{"_id" : NumberInt("1234"), "count" : 1}

我做错了什么?我正在使用 pymongo 3.4 和 python 3.6 和 mongomock 3.7。

我还尝试将1 替换为"1",它不会崩溃,但会给出错误的结果:({"_id" : NumberInt("1234"), "count" : NumberInt("0")})

【问题讨论】:

    标签: python mongodb pymongo pymongo-3.x


    【解决方案1】:

    好吧,显然这是 mongomock 中的一个错误,升级到 3.8 后,我得到了预期的行为。

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 2020-09-17
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      相关资源
      最近更新 更多