如何计算mongodb中嵌套文档中的出现次数? [英] How to count occurrences in nested document in mongodb?

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

问题描述

在数组中嵌套一个数组的情况下,如何计算特定值的数量?例如,我想计算以下文档中的答案"数量.查询应返回有2个苹果和1个香蕉.

In the situation where there is an array nested within an array, how would I count the number of a specific value? For example, I want to count the number of "answers" in the document below. query should return that there are 2 apples and 1 banana.

{
  "_id" : ObjectId("52c1d909fc7fc68ddd999a73"),
  "name" : "Some survey",
  "questions" : [
    {
      "_id" : ObjectId("52c1e250fc7fc68ddd999a75"),
      "answers" :
      [
        {
          "userId" : "some GUIDs",
          "answer" : "apple"
        },
        {
          "userId" : "some GUID",
          "answer" : "apple"
        },
        {
          "userId" : "some GUID",
          "answer" : "banana"
        }
      ],
      "questionText" : "blah blah blah...",
      "questionType" : "multiple choice"
    }
]

}

推荐答案

有几种方法可以解决此问题,具体取决于您需要处理多少数据.您可以在MongoDB 2.2及更高版本中使用聚合框架,也可以使用映射/减少.有关功能和限制的摘要,请参见聚合命令比较.

There are a few ways to approach this depending on how much data you need to process. You could use the Aggregation Framework in MongoDB 2.2+, or possibly Map/Reduce. See Aggregation Commands Comparison for a summary of the features and limitations.

以下是使用聚合框架的示例:

Here's an example using the Aggregation Framework:

db.fruit.aggregate(
    // Limit matching documents (can take advantage of index)
    { $match: {
        "_id" : ObjectId("52c1d909fc7fc68ddd999a73")
    }},

    // Unpack the question & answer arrays
    { $unwind: "$questions" },
    { $unwind: "$questions.answers" },

    // Group by the answer values
    { $group: {
        _id: "$questions.answers.answer",
        count: { $sum: 1 }
    }}
)

对于您的示例文档,返回:

For your sample document this returns:

{
    "result" : [
        {
            "_id" : "banana",
            "count" : 1
        },
        {
            "_id" : "apple",
            "count" : 2
        }
    ],
    "ok" : 1
}

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

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