Update field in exact element array in MongoDB

2018-12-31 09:58发布

I have a document structured like this:

{
    _id:"43434",
    heroes : [
        { nickname : "test",  items : ["", "", ""] },
        { nickname : "test2", items : ["", "", ""] },
    ]
}

Can I $set the second element of the items array of the embedded object in array heros with nickname "test" ?

Result:

{
    _id:"43434",
    heroes : [
        { nickname : "test",  items : ["", "new_value", ""] }, // modified here
        { nickname : "test2", items : ["", "", ""] },
    ]
}

2条回答
人间绝色
2楼-- · 2018-12-31 10:31

You need to make use of 2 concepts: mongodb's positional operator and simply using the numeric index for the entry you want to update.

The positional operator allows you to use a condition like this:

{"heros.nickname": "test"}

and then reference the found array entry like so:

{"heros.$  // <- the dollar represents the first matching array key index

As you want to update the 2nd array entry in "items", and array keys are 0 indexed - that's the key 1.

So:

> db.denis.insert({_id:"43434", heros : [{ nickname : "test",  items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }]});
> db.denis.update(
    {"heros.nickname": "test"}, 
    {$set: {
        "heros.$.items.1": "new_value"
    }}
)
> db.denis.find()
{
    "_id" : "43434", 
    "heros" : [
        {"nickname" : "test", "items" : ["", "new_value", "" ]},
        {"nickname" : "test2", "items" : ["", "", "" ]}
    ]
}
查看更多
不流泪的眼
3楼-- · 2018-12-31 10:51
db.collection.update(
{
heroes:{$elemMatch:{ "nickname" : "test"}}},
 {
     $push: {
        'heroes.$.items': {
           $each: ["new_value" ],
           $position: 1
        }
     }
   }

)
查看更多
登录 后发表回答