简体   繁体   English

聚合-用pymongo计数记录

[英]Aggregate - count records with pymongo

I would like to count matching records with pymongo. 我想用pymongo计算匹配记录。 I have looked up the documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#group-by-month-day-and-year 我已经查看了文档: https : //docs.mongodb.com/manual/reference/operator/aggregation/group/#group-by-month-day-and-year

I understand that I should do something like: 我了解我应该执行以下操作:

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

However, I am getting this error: 但是,我收到此错误:

      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'

Add Comment 添加评论

I would think that pymongo would evaluate it to this mongodb statement: 我认为pymongo会对此mongodb语句进行评估:

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

Which gives me the expected result when ran from mongodb console, which is: {"_id" : NumberInt("1234"), "count" : 1} in my case. 从mongodb控制台运行时,这给了我预期的结果,在我的情况下为{"_id" : NumberInt("1234"), "count" : 1}

What am I doning wrong? 我在做什么错? I am using pymongo 3.4 and python 3.6 and mongomock 3.7. 我正在使用pymongo 3.4和python 3.6和mongomock 3.7。

I have also tried replacing 1 with "1" which does not crash, but gives an incorrect result: ( {"_id" : NumberInt("1234"), "count" : NumberInt("0")} ) 我也尝试过将1替换为"1" ,这不会崩溃,但给出了错误的结果:( {"_id" : NumberInt("1234"), "count" : NumberInt("0")}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM