计算嵌套mongodb文档中的出现次数并保留组 [英] Count occurrences in nested mongodb document and keeping group

查看:62
本文介绍了计算嵌套mongodb文档中的出现次数并保留组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些文件:

[
  {
      "question": 1,
      "answer": "Foo"
  },
  {
      "question": 1,
      "answer": "Foo"
  },
  {
      "question": 1,
      "answer": "Bar"
  },
  {
      "question": 2,
      "answer": "Foo"
  },
  {
      "question": 2,
      "answer": "Foobar"
  }
]

在后端(php)中,我需要获取答案的分区,例如:

And in my backend (php) I need to get the repartition of answers, something like:

  • 问题1:

  • Question 1:

  • "Foo":2/3
  • 酒吧":1/3

问题2:

  • "Foo":1/2
  • "Foobar":1/2

目前,我只想运行mongo查询以实现此结果:

For now I just want to run a mongo query in order to achieve this result:

[
  {
      "question": 1,
      "answers": {
          "Foo": 2,
          "Bar": 1
      }
  },
  {
      "question": 2,
      "answers": {
          "Foo": 1,
          "Foobar": 1
      }
  }
 ]

这是我想出的:

db.getCollection('testAggregate').aggregate([{
    $group: {
        '_id': '$question',
        'answers': {'$push': '$answer'},
    }
}
]);

它返回:

{
    "_id" : 2.0,
    "answers" : [ 
        "Foo", 
        "Foobar"
    ]
},{
    "_id" : 1.0,
    "answers" : [ 
        "Foo", 
        "Foo", 
        "Bar"
    ]
}

现在我需要对Answers字段执行$ group操作以计算出现的次数,但是我需要按问题保留group,但我不知道该怎么做.有人可以帮我吗?

And now I need to to a $group operation on the answers field in order to count the occurences, but I need to keep the group by question and I do not know how to do it. Could someone give me a hand?

推荐答案

您可以使用以下聚合.

按问题和答案分组以获取合并计数,然后按问题分组以获取答案及其计数.

Group by both question and answer to get the count for combination followed by group by question to get the answer and its count.

db.getCollection('testAggregate').aggregate([
  {"$group":{
    "_id":{"question":"$question","answer":"$answer"},
    "count":{"$sum":1}
  }},
  {"$group":{
    "_id":"$_id.question",
    "answers":{"$push":{"answer":"$_id.answer","count":"$count"}}
  }}
]);

您可以使用以下代码在3.4中获取所需的格式.

You can use below code to get the format you want in 3.4.

$group键更改为k和v,后跟 $addFields $arrayToObject 将数组转换为命名键值对.

Change $group keys into k and v followed by $addFields with $arrayToObject to transform the array into named key value pairs.

db.getCollection('testAggregate').aggregate([
  {"$group":{
    "_id":{"question":"$question","answer":"$answer"},
    "count":{"$sum":1}
  }},
  {"$group":{
    "_id":"$_id.question",
    "answers":{"$push":{"k":"$_id.answer","v":"$count"}}
  }},
 {"$addFields":{"answers":{"$arrayToObject":"$answers"}}}
]);

这篇关于计算嵌套mongodb文档中的出现次数并保留组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆