更新 MongoDB 中嵌套对象数组中对象中键的值

Update value of key in Object in nested array of objects in MongoDB

我正在尝试更新“array1.array2._id”的数据:ObjectId("627a6fab60dc3c523b396af1") 并将名称设置为 John 但它正在将所有 array2 的第一个元素的名称更新为 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")
        }
    ]
}

基于@R2D2 的,您可以:

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

如您所见this playground example