gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:00:59 26 4
gpt4 key购买 nike

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

最佳答案

有几种方法可以解决这个问题,具体取决于您需要处理的数据量。你可以使用 Aggregation Framework在 MongoDB 2.2+ 中,或者可能是 Map/Reduce .参见 Aggregation Commands Comparison有关功能和限制的摘要。

这是一个使用聚合框架的示例:

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
}

关于mongodb - 如何计算mongodb中嵌套文档的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20850824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com