Mongo db updateOne to update a list of documents using a list of document

263 Views Asked by At

I have a document like this

{
  "_id" : ObjectId("5f90be124e3e00bdfcc0e32f"),
  "data": [
    {"id": "id1", "value": "value1"},
    {"id": "id2", "value": "value2"},
    {"id": "id3", "value": "value3"},
    {"id": "id4", "value": "value4"},
    {"id": "id5", "value": "value5"}
  ],
  "extra_value": "Testing",
  "extra_value1": "Testing1"
}

and I want to update it with

{
  "_id" : ObjectId("5f90be124e3e00bdfcc0e32f"),
  "data": [
    {"id": "id3", "value": "value3-updated"},
    {"id": "id5", "value": "value5-updated"},
    {"id": "id6", "value": "value6"}
  ],
  "extra_value1": "Testing1-updated"
}

so the extra_value1 must be updated, the two ids i.e. 3 and 5 must be updated, but since there doesn't exist the id6 it should be added to the document. The final document would look something like this.

{
  "_id" : ObjectId("5f90be124e3e00bdfcc0e32f"),
  "data": [
    {"id": "id1", "value": "value1"},
    {"id": "id2", "value": "value2"},
    {"id": "id3", "value": "value3-updated"},
    {"id": "id4", "value": "value4"},
    {"id": "id5", "value": "value5-updated"},
    {"id": "id6", "value": "value6"}
  ],
  "extra_value": "Testing",
  "extra_value1": "Testing1-updated"
}

I could do it with multiple update queries, but could not do it all in a single query. Is there a way to do such a thing? Thank you

1

There are 1 best solutions below

0
On

Try this -

db.collection.updateMany(
  {_id:ObjectId("5f90be124e3e00bdfcc0e32f") },
  [{
    $set: {
      data: {
        $map: {
          input: "$data",
          in: {
            $mergeObjects: [
              "$$this",
              {
                $cond: [
                  { $eq: ["$$this.id", "id3"] },
                  { value: "value3-updated" },
                  {$cond: [
                      {$eq: ["$$this.id", "id5"]},
                      {value: "value5-updated"},
                      {}
                      ]}
                ]
              }
            ]
          }
        }
      },
      "extra_value1" : "Testing1-updated"
    }
  }
      ]
)

This would perform all the updates for id3, id5 and extra_value1 field but still would not add new entry for id6.

Spent quite a bit of time to get it added. But no luck. I don't know that is even possible or not.

Still I hope the above query would be helpful. Thanks!!