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

4

当数组嵌套在另一个数组中时,如何计算特定值的数量?例如,我想在下面的文档中计算“answers”的数量。查询应返回有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"
    }
]

}

2个回答

7

根据需要处理的数据量,有几种方法可以解决这个问题。您可以在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 }
    }}
)

对于您的示例文档,这将返回:
{
    "result" : [
        {
            "_id" : "banana",
            "count" : 1
        },
        {
            "_id" : "apple",
            "count" : 2
        }
    ],
    "ok" : 1
}

0

这里有一种使用聚合框架的方法来解决问题。一旦你学会了它,你就可以在数据处理方面做很多好事。

db.so.aggregate([{$unwind:"$questions"}, {$unwind:"$questions.answers"}, {$group:{_id:"$questions.answers.answer", fruit_count:{$sum:1}}}])

给我这个。
{
    "result" : [
        {
            "_id" : "banana",
            "fruit_count" : 1
        },
        {
            "_id" : "apple",
            "fruit_count" : 2
        }
    ],
    "ok" : 1

为了确保万无一失,我添加了这个文档:
db.so.insert({
  "_id" : ObjectId("52c1d909fc7fc68ddd999a75"),
  "name" : "Some survey",
  "questions" : [
    {
      "_id" : ObjectId("52c1e250fc7fc68ddd999a75"),
      "answers" :
      [
        {
          "userId" : "some GUIDs",
          "answer" : "orange"
        },
        {
          "userId" : "some GUID",
          "answer" : "orange"
        },
        {
          "userId" : "some GUID",
          "answer" : "banana"
        }
      ],
      "questionText" : "blah blah blah...",
      "questionType" : "multiple choice"
    }
]
})

我的查询现在给了我:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接