0

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")
        }
    ]
}
2

1 Answer 1

2

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

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.