-3

Update nested object values in array, we have multiple objects in array.

{ 
    "_id" : ObjectId("5a7e395e20a31e44e0e7e284"), 
    "name" : "a", 
    "address" : [
        {
            "street" : "123", 
            "town" : "bar"
        }, 
        {
            "street" : "Lower Street", 
            "town" : "bar"
        }, 
        {
            "street" : "123", 
            "town" : "foo"
        }
    ]
}

Need to update town is HNO if street is 123.

2
  • I have run this query but its updated all objects. db.coll.updateMany({"address.street": 123, {$set: { "town": "HNO"}}}) Commented Jan 10 at 11:47
  • This question is similar to: How do you update objects in a document's array (nested updating). If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jan 10 at 14:52

1 Answer 1

1

Use positional filtered operator $[<identifier] to update the matching element in the array.

db.collection.updateMany({
  "address.street": "123"
},
{
  $set: {
    "address.$[a].town": "HNO"
  }
},
{
  arrayFilters: [
    {
      "a.street": "123"
    }
  ]
})

Demo @ Mongo Playground

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.