对对象内的所有字段求和

时间:2017-07-30 14:00:17

标签: mongodb nosql

我正在尝试在MongoDB中构建一个项目(我的第一个项目)。我有以下结构:

 {
    "_id" : 1,
    "week" : "1",
"Unit" : {
    "Name" : "Area1",
    "Name sub" : "Area1",
    "Center name" : "Fuysam",
    "Center type" : "Branch",
    "Perm" : {
        "GOP sales" : 6,
        "GOP recruiters" : 2,
        "GOP permmanent" : 1,
        "GOP admins" : 6,
        "GOP coordinator" : 2,
        "GOP support" : 1,
        "GOP others" : 0
    },
    "Plan" : {
        "Temps New" : 26,
        "OU New" : 21,
        "Temps Lost" : 5,
        "OU Lost" : 7,
        "Current week" : 128,
        "Outsourcing" : 332,
        "L Clients" : 351,
        "M Clients" : 65,
        "S Clients" : 44,
        "Position closed" : 1
    }
  }

是否可以在每个对象中添加一个Total字段,以便自动添加所有字段? (我的字段编号是动态的,在第2周我可能有5个字段,在第3周我可能有9个字段,依此类推。) 像这样:

 "Perm" : {
        "GOP sales" : 6,
        "GOP recruiters" : 2,
        "GOP permmanent" : 1,
        "GOP admins" : 6,
        "GOP coordinator" : 2,
        "GOP support" : 1,
        "GOP others" : 0,
       "GOP Total" : "GOP sales" + "GOP recruiters" + "GOP permmanent" + "GOP admins"......
    }

如果可以这样做,你能举个例子吗? 非常感谢你。

1 个答案:

答案 0 :(得分:3)

您可以使用以下查询来实现您的目标:

collection.aggregate
(
  {
    $addFields:
    {
      // we want to add a new field into the embedded "Unit.Perm" document and call it "GDP Total"
      "Unit.Perm.GDP Total":
      {
        // In order to calculate the value of our new field we need to "reduce"/sum up all our existing document's properties into one single value
        $reduce:
        {
          input:
          {
            // transform the embedded document "Unit.Perm" into an array of key-value-pairs
            $objectToArray: "$Unit.Perm"
          },
          initialValue: 0,
          in: { $sum: [ "$$value", "$$this.v" ] }
        }
      }
    }
  }
)