1

I'm trying to build a project in MongoDB (my first project). I have the following structure :

 {
    "_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
    }
  }

Is it posible to add a Total field in every object in order to add automatically all of my fields ? (My fields number is dynamic, in week 2 I may have 5 fields, in week 3 I may have 9 fields and so on.) Something like this :

 "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"......
    }

If it is possible to do this, can you give me an example ? Thank you very much.

Community
  • 1
  • 1
k4br4s
  • 127
  • 8

1 Answers1

3

You can use the following query to achieve what you want:

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
  • 10,733
  • 1
  • 19
  • 34