更新MongoDB中精确元素数组中的字段 [英] Update field in exact element array in MongoDB

查看:44
本文介绍了更新MongoDB中精确元素数组中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构如下的文件:

I have a document structured like this:

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

我可以使用nickname "test"$set嵌入对象heros中的嵌入对象items数组的第二个元素吗?

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

结果:

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

推荐答案

您需要使用2个概念:

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

当您要更新"items"中的第二个数组条目时,数组键被索引为0,即键1.

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

所以:

> 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" : ["", "", "" ]}
    ]
}

这篇关于更新MongoDB中精确元素数组中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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