如何计算mongodb嵌套文档中的出现次数?

use*_*123 4 mongodb mongodb-query aggregation-framework

在数组中嵌套数组的情况下,如何计算特定值的数量?比如我想统计下面文档中“答案”的数量。查询应该返回有 2 个苹果和 1 个香蕉。

{
  "_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"
    }
]
Run Code Online (Sandbox Code Playgroud)

}

Ste*_*nie 6

有几种方法可以解决这个问题,具体取决于您需要处理的数据量。您可以使用MongoDB 2.2+ 中的聚合框架,或者可能使用Map/Reduce。有关功能和限制的摘要,请参阅聚合命令比较

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

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 }
    }}
)
Run Code Online (Sandbox Code Playgroud)

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

{
    "result" : [
        {
            "_id" : "banana",
            "count" : 1
        },
        {
            "_id" : "apple",
            "count" : 2
        }
    ],
    "ok" : 1
}
Run Code Online (Sandbox Code Playgroud)