总结mongodb中多个子文档的值 [英] sum up value from multiple subdocuments in mongodb
问题描述
我具有以下数据结构:
{
"_id" : ObjectId("4e96f771e016b98aa63d88c9"),
"goals" : {
"4809" : {
"VisitsBeforeGoal" : 12,
"pagesBeforeGoal" : 16
},
"4810" : {
"VisitsBeforeGoal" : 2,
"pagesBeforeGoal" : 6
},
"4811" : {
"VisitsBeforeGoal" : 3,
"pagesBeforeGoal" : 8
}
},
"totalPages" : 246,
"totalVisits" : 114
}
4809、4810和4811是未知的目标ID,例如
4809, 4810 and 4811 is goalID's that are not know, e.g. dynamic.
现在,我要获取的是每个目标的 VisitsBeforeGoal和 pagesBeforeGoal的总和。
Now what i want is to get the sum of "VisitsBeforeGoal" on each goal and "pagesBeforeGoal" and a sum of goals. Something like:
{
goals:[
{
"goalID" : 4809,
"VisitsBeforeGoal" : 245,
"pagesBeforeGoal" : 632,
"sum" : 45,
}
]
}
我似乎不知道如何进入每个子文档,因为我不知道goalID。我尝试过类似 goals。$。VisitsBeforeGoal的操作,但这似乎不起作用。
I cant seem to figure out how to get into each subdocument, as i dont know the goalID. I tried somehting like "goals.$.VisitsBeforeGoal" but that did not seem to work.
推荐答案
您的数据结构存在问题。为了使 goals。$。VisitsBeforeGoal
起作用,您需要一个数组。因此,您的结构必须为
Your data structure is problematical. In order to make goals.$.VisitsBeforeGoal
work, you need an array. So your structure must be
"goals" : [ {
"id" : 4809,
"VisitsBeforeGoal" : 12,
"pagesBeforeGoal" : 16
},
{
"id" : 4810,
"VisitsBeforeGoal" : 2,
"pagesBeforeGoal" : 6
},
{
"id" : 4811,
"VisitsBeforeGoal" : 3,
"pagesBeforeGoal" : 8
}
]
使用动态键不是一个好的选择。如果您有机会更改自己的结构,我建议您更改它。
Working with dynamic keys is not a good choice. If you have chance to change your structure, I would advice you to change it.
这篇关于总结mongodb中多个子文档的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!