汇总mongodb中多个子文档的值

汇总mongodb中多个子文档的值,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有以下数据结构: { "_id" : ObjectId("4e96f771e016b98aa63d88c9"), "goals" : { "4809" : { "VisitsBeforeGoal" : 12, "pagesBeforeGoal" : 16 }, "4810" : { "VisitsBeforeGoal" : 2, "pagesBeforeGoal" : 6 }, "4811" : {

我有以下数据结构:

{
  "_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是不知道的守门员,例如动态

现在我想得到的是每个目标上的“VisitsBeforeGoal”和“pagesBeforeGoal”以及目标的总和。比如:

{
  goals:[
    {
          "goalID" : 4809,
          "VisitsBeforeGoal" : 245,
          "pagesBeforeGoal" : 632,
          "sum" : 45,    
    }
  ]
}

我似乎不知道如何进入每个子文档,因为我不知道目标。我尝试了一些类似“goals.$.VisitsBeforeGoal”的方法,但似乎不起作用。

您的数据结构有问题。为了使
目标。$.VisitsBeforeGoal
起作用,您需要一个数组。所以你的结构必须是

"goals" : [ {
        "id" : 4809,
        "VisitsBeforeGoal" : 12,
        "pagesBeforeGoal" : 16
    },
    {
        "id" : 4810,
        "VisitsBeforeGoal" : 2,
        "pagesBeforeGoal" : 6
    },
    {
        "id" : 4811,
        "VisitsBeforeGoal" : 3,
        "pagesBeforeGoal" : 8
    }
]

使用动态关键点不是一个好选择。如果您有机会更改您的结构,我建议您更改它。

此数据结构的原因是我需要在同一查询中$inc多个目标,如:{$inc:{goals.4810.pagebeforegal:3,goals.4811.pagebeforegal:6}因此,如果目标是array.right,那么我不能使用$elemMatch-使用目标作为键允许简单的更新/升级-您建议的模式更容易查询,但很难更新。请参阅此处的另一面问题:您能否在聚合之前查询以获取所有目标键?@AsyaKamsky Yes。我可以使用map/reduce在脚本中获取此信息。有什么想法吗?如果你知道字段名,那么你可以通过聚合来实现。今天晚些时候我将发布一个示例。