3

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!

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.