Update field in exact element array in MongoDB

后端 未结 3 793
执念已碎
执念已碎 2020-11-22 07:19

I have a document structured like this:

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


        
3条回答
  •  无人及你
    2020-11-22 07:34

    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:

    {"heroes.nickname": "test"}
    

    and then reference the found array entry like so:

    {"heroes.$  // <- 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", 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" : ["", "", "" ]}
        ]
    }
    

提交回复
热议问题