在MongoDB中更新数组元素的值 [英] Updating Value of Array Element in MongoDB

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

问题描述

我想知道如何更新数组"array_of_stuff"中名称"字段标识的元素之一的值"字段.例如,我想将"name_of_thing_1"的值更新为"new_value_of_thing_1".如何使用更新命令的第二个参数(即,更新参数)执行此操作.我正在重新使用内部编写的类库,但我无法控制update命令的第一个参数(即查询参数).这可能吗?

I'd like to know how to update the "value" field of one of the elements identified by the "name" field in the array "array_of_stuff". For example, I want to update the value for "name_of_thing_1" to "new_value_of_thing_1". How can I do this ONLY using the second parameter (i.e. the update parameter) to the update command. I am re-using a class library written in-house I don't have control over the first argument to the update command (i.e. the query parameter). Is this possible?

{
"array_of_stuff": [
    {
        "name": "name_of_thing_1",
        "value": "value_of_thing_1",           
    },
    {
        "name": "name_of_thing_2",
        "value": "value_of_thing_2",
    }
]
}

感谢您的帮助!

推荐答案

您可以像这样更新数组中单个项目的值(如果您知道其索引):

You can update the value of a single item in an array (if you know its index) like this:

db.stuff.update(/* query ... */, {$set:{"arrayname.<index>":new_value}})

如果您的数组包含文档,则可以在该索引处更新文档的特定字段,如下所示:

If your array contains documents, you can update a particular field of a document at that index like this:

db.stuff.update(/* query ... */, {$set:{"array_of_stuff.0.value":"new_value_of_thing_1"}})

// If you could use the query parameter and knew something
// about the value in the array you wanted to change:
db.stuff.update({"array_of_stuff.value":"value_of_thing_1"}, {$set:{"array_of_stuff.$.value":"new_value_of_thing_1"}})

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

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