根据 MongoDB 中的属性更新嵌套数组对象 [英] Update nested array objects based on a property in MongoDB
问题描述
我有一个 MongoDB 集合,其中包含如下所示的文档:
I have a MongoDB collection which has documents which look like this:
{
createdTimestamp: 111111111111,
items: [{
itemName: 'Name 1',
quantity: 10
}, {
itemName: 'Name 2'
quantity: 20
}]
}
现在,我想更新所有文档,以便 itemName: 'Name 1'
将更新为 itemName: 'New Name'
.更新后,上述文件应如下所示:
Now, I want to update all documents so that itemName: 'Name 1'
would be updated to itemName: 'New Name'
.
After an update, the above document should look like as below:
{
createdTimestamp: 111111111111,
items: [{
itemName: 'New Name',
quantity: 10
}, {
itemName: 'Name 2'
quantity: 20
}]
}
有没有办法做到这一点,而无需自己遍历所有文档?
Is there any way to do this, without iterating over all documents myself?
推荐答案
您需要使用 $ positional
操作符更新数组元素,使用 multi: true
选项,你可以更新多个具有相同匹配的文档
You need to use $ positional
operator to update an array element and with multi: true
option you can update multiple document with the same match
db.collection.update(
{ 'items': { '$elemMatch': { 'itemName': 'Name 1' }}},
{ '$set': { 'items.$.itemName': 'New Name' }},
{ 'multi': true }
)
和 mongodb 3.6 arrayFilters
and with the mongodb 3.6 arrayFilters
db.collection.update(
{ 'items': { '$elemMatch': { 'itemName': 'Name 1' }}},
{ '$set': { 'items.$[item].itemName': 'New Name' }},
{ 'arrayFilter': [{ 'item.itemName': 'Name 1' }], 'multi': true }
)
这篇关于根据 MongoDB 中的属性更新嵌套数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!