Home > Back-end >  Update value of key in Object in nested array of objects in MongoDB
Update value of key in Object in nested array of objects in MongoDB

Time:05-12

I am trying to update data of "array1.array2._id": ObjectId("627a6fab60dc3c523b396af1") and Set Name to John But it's updating in all array2's first element's name to John.

db.getCollection('tests')
.updateOne({ "array1.array2._id": ObjectId("627a6fab60dc3c523b396af1") },{ $set: { "array1.$[].array2.$.name" : "John" } })

{
    "_id" : ObjectId("627a6fab60dc3c523b396aec"),
    "array1" : [ 
        {
            "array2" : [ 
                {
                    "_id" : ObjectId("627a6fab60dc3c523b396af1"),
                    "name" : "test"
                }, 
                {
                    "_id" : ObjectId("627a6fab60dc3c523b396af2"),
                    "name" : "ABC"
                }
            ],
            "_id" : ObjectId("627a6fab60dc3c523b396aed")
        }, 
        {
            "array2" : [ 
                {
                    "_id" : ObjectId("627a6fab60dc3c523b396af3"),
                    "name" : "XYZ"
                }, 
                {
                    "_id" : ObjectId("627a6fab60dc3c523b396af4"),
                    "name" : "Testing"
                }
            ],
            "_id" : ObjectId("627a6fab60dc3c523b396aee")
        }
    ]
}

CodePudding user response:

Based on this great answer by @R2D2, you can do:

db.collection.update({
  "array1.array2._id": ObjectId("627a6fab60dc3c523b396af1")
},
{
  $set: {
    "array1.$[].array2.$[y].name": "John"
  }
},
{
  arrayFilters: [
    {
      "y._id": ObjectId("627a6fab60dc3c523b396af1")
    }
  ]
})

As you can see on this playground example

  • Related