sum up value from multiple subdocuments in mongodb

五迷三道 提交于 2020-01-17 03:36:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!