Search code examples
mongodbaggregation

Add field to every object in array of objects in mongo aggregation


I have one field in schema at root level and want to add it in every object from array which matches a condition.

Here is a sample document....

{
    calls: [
      {
        "name": "sam",
        "status": "scheduled"
      },
      {
        "name": "tom",
        "status": "cancelled"
      },
      {
        "name": "bob",
        "status": "scheduled"
      },
      
    ],
    "time": 1620095400000.0,
    "call_id": "ABCABCABC"
}

Required document is as follows:

[
  {
    "call_id": "ABCABCABC",
    "calls": [
      {
        "call_id": "ABCABCABC",
        "name": "sam",
        "status": "scheduled"
      },
      {
        "name": "tom",
        "status": "cancelled"
      },
      {
        "call_id": "ABCABCABC",
        "name": "bob",
        "status": "scheduled"
      }
    ],
    "time": 1.6200954e+12
  }
]

The call_id should be added to all objects in array whose status is "scheduled". Is it possible to do this with mongo aggregation? I have tried $addFields but was unable to achieve above result. Thanks in advance!


Solution

  • Here is how I would do it using $map and $mergeObjects

    db.collection.aggregate([
      {
        "$addFields": {
          calls: {
            $map: {
              input: "$calls",
              as: "call",
              in: {
                $cond: [
                  {
                    $eq: [
                      "$$call.status",
                      "scheduled"
                    ]
                  },
                  {
                    "$mergeObjects": [
                      "$$call",
                      {
                        call_id: "$call_id"
                      }
                    ]
                  },
                  "$$call"
                ]
              }
            }
          }
        }
      }
    ])
    

    Mongo Playground