【问题标题】:Sum all fields inside an object [duplicate]对对象内的所有字段求和[重复]
【发布时间】:2017-07-30 14:00:16
【问题描述】:

我正在尝试在 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"......
    }

如果可以做到这一点,你能给我举个例子吗? 非常感谢。

【问题讨论】:

    标签: mongodb nosql


    【解决方案1】:

    您可以使用以下查询来实现您想要的:

    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" ] }
            }
          }
        }
      }
    )
    

    【讨论】:

    • 非常感谢@dnickless。它就像一个魅力。你是男人!
    猜你喜欢
    • 2015-11-06
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2020-06-02
    相关资源
    最近更新 更多