问题
I have the following datastructure:
{
"_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 and 4811 is goalID's that are not know, e.g. dynamic.
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,
}
]
}
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.
回答1:
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.
来源:https://stackoverflow.com/questions/19996622/sum-up-value-from-multiple-subdocuments-in-mongodb