Add field to $map entry in MongoDB

Viewed 372

I have MongoDB collection items with following document:

{
    "values": [
        { "number1": 5, "number2": 6, "anotherProp": "...", "anotherProp2": "..." },
        { "number1": 8, "number2": 1, "anotherProp": "...", "anotherProp2": "..." }
    ]
}

Is there any way to add sum property to each item of values (sum = number1 + number2)? I would like to avoid naming all other properties (number1, number2, anotherProp, anotherProp2, ...), only add new one (sum). My current solution is:

db.items.aggregate([{
    $project: {
        values: {
            $map: {
                input: "$values",
                as: "v",
                in: {
                    sum: {$add: ["$$v.number1", "$$v.number2"]},
                    number1: "$$v.number1", // This and next 3 lines I would like to omit.
                    number2: "$$v.number2",
                    anotherProp: "$$v.anotherProp",
                    anotherProp2: "$$v.anotherProp2"
                }
            }
        }
    }
}])

Desired result is:

{
    "values": [
        { "number1": 5, "number2": 6, "anotherProp": "...", "anotherProp2": "...", "sum": 11 },
        { "number1": 8, "number2": 1, "anotherProp": "...", "anotherProp2": "...", "sum": 9 }
    ]
}

Is there any way to do this? I tried use $addFields instead of $project, however result is same.

1 Answers

Yes, you can use $mergeObjects

db.collection.aggregate([
  {
    $project: {
      values: {
        $map: {
          input: "$values",
          as: "v",
          in: {
            "$mergeObjects": [
              {
                sum: {
                  $add: [
                    "$$v.number1",
                    "$$v.number2"
                  ]
                }
              },
              "$$v"
            ]
          }
        }
      }
    }
  }
])

MongoPlayground

Related