Skip to content
Advertisement

Add the sum of two fields to a new field in the document

I would like to calculate sum of two fields, then create new field in document something like: ‘totalSum’. But I dont know how to do this. All in mongodb. Here’s an example:

    const obj = {
      name: 'John',
      foo: {
        fooA: 8753.19,
        fooB: 8753.19,
      },
      bar: {
        barA: 196.99,
        barB: 196.99,
      },
    };
    
    //Should be:
    const obj = {
      name: 'John',
      foo: {
        fooA: 8753.19,
        fooB: 8753.19,
        total: fooA+fooB
      },
      bar: {
        barA: 196.99,
        barB: 196.99,
        total: barA+barB
      },
    };

Advertisement

Answer

Demo – https://mongoplayground.net/p/40DnYmMnEyU

Use $addFields to add new fileds total, compute values using $add

db.collection.aggregate({
  $addFields: {
    "foo.total": { $add: [ "$foo.fooA", "$foo.fooB" ] },
    "bar.total": { $add: [ "$bar.barA", "$bar.barB" ] }
  }
})

Output

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "bar": {
      "barA": 196.99,
      "barB": 196.99,
      "total": 393.98
    },
    "foo": {
      "fooA": 8753.19,
      "fooB": 8753.19,
      "total": 17506.38
    },
    "name": "John"
  }
]
Advertisement