更新MongoDB中数组内部数组中的嵌入式对象 [英] Update embedded object inside array inside array in MongoDB

查看:281
本文介绍了更新MongoDB中数组内部数组中的嵌入式对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似文件

{
    id : 100,
    heros:[
        {
           nickname : "test",
           spells : [
             {spell_id : 61, level : 1},
             {spell_id : 1, level : 2}
           ]
        }
    ]
}

我不能用spells内的spell_id : 1level : 3level : 3拼写level : 3的昵称为"test"的level : 3.我尝试了以下查询:

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}});

我看到的错误是

无法使用字符串字段名称[spells]追加到数组 感谢您的帮助.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆