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

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

问题描述

我有一个这样结构的文档:

I have a document structured like this:

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

我可以$setnickname数组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 个概念:mongodb 的位置运算符 并简单地使用要更新的条目的数字索引.

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

因为您想更新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", 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" : ["", "", "" ]}
    ]
}

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

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