Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

Update embedded object inside array inside array in MongoDB

I have document like

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

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

Errror i see is

can't append to array using string field name [spells] Thanks for help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...