在 MongoDB 中的数组内更新数组内的嵌入对象 [英] Update embedded object inside array inside array in MongoDB
本文介绍了在 MongoDB 中的数组内更新数组内的嵌入对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的文档
{
id : 100,
heros:[
{
nickname : "test",
spells : [
{spell_id : 61, level : 1},
{spell_id : 1, level : 2}
]
}
]
}
我不能在 spells
里面用 spell_id : 1
来$set
拼写的 level : 3
code>heros 昵称test.我试过这个查询:
I can't $set
spell's level : 3
with spell_id : 1
inside spells
that inside heros
with nickname "test. I tried this query:
db.test.update({"heros.nickname":"test", "heros.spells.spell_id":1},
{$set:{"heros.spells.$.level":3}});
我看到的错误是
无法使用字符串字段名称附加到数组 [拼写]感谢您的帮助.
can't append to array using string field name [spells] Thanks for help.
推荐答案
您只能将 $
位置运算符用于单级数组.在您的情况下,您有一个嵌套数组(heros
是一个数组,其中每个英雄都有一个 spells
数组).
You can only use the $
positional operator for single-level arrays. In your case, you have a nested array (heros
is an array, and within that each hero has a spells
array).
如果您知道数组的索引,则可以在进行更新时使用显式索引,例如:
If you know the indexes of the arrays, you can use explicit indexes when doing an update, like:
> db.test.update({"heros.nickname":"test", "heros.spells.spell_id":1}, {$set:{"heros.0.spells.1.level":3}});
这篇关于在 MongoDB 中的数组内更新数组内的嵌入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文