根据MongoDB中的属性更新嵌套数组对象 [英] Update nested array objects based on a property in MongoDB
本文介绍了根据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?
推荐答案
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屋!
查看全文