我的文档结构如下:
{
_id:"43434",
heroes : [
{ nickname : "test", items : ["", "", ""] },
{ nickname : "test2", items : ["", "", ""] },
]
}
我可以$set
数组heros
中嵌入对象的items
数组的第二个元素与nickname
“测试”
?
结果:
{
_id:"43434",
heroes : [
{ nickname : "test", items : ["", "new_value", ""] }, // modified here
{ nickname : "test2", items : ["", "", ""] },
]
}
最佳答案
您需要使用两个概念:mongodb's positional operator并且只需使用要更新的条目的数字索引。
位置运算符允许您使用这样的条件:
{"heroes.nickname": "test"}
然后像这样引用找到的数组条目:
{"heroes.$ // <- the dollar represents the first matching array key index
当您要更新“items”中的第二个数组条目时,数组键的索引为 0 - 这就是键 1。
所以:
> db.denis.insert({_id:"43434", heroes : [{ nickname : "test", items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }]});
> db.denis.update(
{"heroes.nickname": "test"},
{$set: {
"heroes.$.items.1": "new_value"
}}
)
> db.denis.find()
{
"_id" : "43434",
"heroes" : [
{"nickname" : "test", "items" : ["", "new_value", "" ]},
{"nickname" : "test2", "items" : ["", "", "" ]}
]
}
https://stackoverflow.com/questions/10432677/