简体   繁体   English

如何在MongoDB中查找和计数特定项目?

[英]How to find and count in MongoDB for specific items?

I would like to count the total number of each type of responses associated with each ID in the following JSON result that I am extracting from MongoDB: 我想在从MongoDB中提取的以下JSON结果中计算与每个ID相关的每种响应类型的总数:

{
  "test": [
    {
      "ID": 4, 
      "response": "A"
    }, 
    {
      "ID": 4, 
      "response": "B"
    }, 
    {
      "ID": 1, 
      "response": "A"
    }, 
    {
      "ID": 3, 
      "response": "B"
    }, 
    {
      "ID": 2, 
      "response": "C"
    }
  ]
}
// and so on...

So for example, I would like to structure the JSON into something like this: 因此,例如,我想将JSON构造成如下形式:

{
    "test": [
        {
            "ID": 4,
            "A": 1,
            "B": 1
        },
        {
            "ID": 3,
            "B": 1
        },
        {
            "ID": 2,
            "C": 1
        },
        {
            "ID": 1,
            "A": 1
        }
    ]
}

My query looks something like this because I was just testing and trying to tally responses just for ID 4. 我的查询看起来像这样,因为我只是测试并试图对ID 4的响应进行计数。

surveyCollection.find({"ID":4},{"ID":1,"response":1,"_id":0}).count():

But I get the following error: TypeError: 'int' object is not iterable 但是我收到以下错误: TypeError: 'int' object is not iterable

What you need is use the "aggregation framework" 您需要的是使用“聚合框架”

surveyCollection.aggregate([
    {"$unwind": "$test" }, 
    {"$group": {"_id": "$test.ID", "A": {"$sum": 1}, "B": {"$sum": 1}}},
    {"$group": {"_id": None, "test": {"$push": {"ID": "$ID", "A": "$A", "B": "$B"}}}}
])

From pymongo 3.x the aggregate() method returns a CommandCursor over the result set so you may need to convert it first into list. 从pymongo 3.x开始,gregation aggregate()方法在结果集上返回CommandCursor ,因此您可能需要先将其转换为列表。

In [16]: test
Out[16]: <pymongo.command_cursor.CommandCursor at 0x7fe999fcc630>

In [17]: list(test)
Out[17]: 
[{'_id': None,
  'test': [{'A': 1, 'B': 1},
   {'A': 1, 'B': 1},
   {'A': 1, 'B': 1},
   {'A': 2, 'B': 2}]}]

Use return list(test) instead 使用return list(test)代替

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

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