0

How can I update nested array by list key value?

{
    "_id": "mainId",
    "events": [{
            "id": 1,
            "profile": 10,
        } {
            "id": 2,
            "profile": 10,
        } {
            "id": 3,
            "profile": 20,
        }
    ]
}

and I have a list to update:

var list = {id: 2, newval: 222}, {id: 3, newval: 333}

How can I do an update in one query? Or in MongoDB, it will be like a loop?

for({id, val} in list){
     update({_id: "mainId", events.$.id: id}, {setField: {events.$.profile: val}})
}

1 Answer 1

1

If you have a copy of the events array, you could make the necessary updates in your code and then send the updated array to MongoDB in a single query. Something like this

db.Test.updateOne({_id: "mainId"}, {$set: { "events": [{id: 1, profile: 222}, {id: 2, profile: 10}, {id: 3, profile: 333}] } } )

If you don't have a copy of the events array, you could do a bulk operation. Something like

db.Test.bulkWrite(
  [

     { updateOne : {
        "filter": {_id: "mainId", "events.id": 1}, 
        "update": { $set: { "events.$.profile": 222 } }
     }
     },
     { updateOne : {
        "filter": {_id: "mainId", "events.id": 3}, 
        "update": { $set: { "events.$.profile": 333 }}
     }
     }
  ]
)

For more on bulkWrite, see the MongoDB docs: https://docs.mongodb.com/manual/core/bulk-write-operations/#bulkwrite-methods

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

1 Comment

yes. i know only part of array. second example fits, thx. But mb can it do with new futures as pipline update in 4.2+ version ?!

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.