mongodb - 更新 MongoDB 中精确元素数组中的字段

我的文档结构如下:

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

我可以$set数组heros中嵌入对象的items数组的第二个元素与nickname “测试” ?

结果:

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

最佳答案

您需要使用两个概念:mongodb's positional operator并且只需使用要更新的条目的数字索引。

位置运算符允许您使用这样的条件:

{"heroes.nickname": "test"}

然后像这样引用找到的数组条目:

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

当您要更新“items”中的第二个数组条目时,数组键的索引为 0 - 这就是键 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" : ["", "", "" ]}
    ]
}

https://stackoverflow.com/questions/10432677/

相关文章:

mongodb - MongoDB 3.0 中的“无法取消链接套接字文件”错误

node.js - Mongodb的僧侣vs Mongoose

javascript - 我可以确定一个字符串是否是 MongoDB ObjectID 吗?

javascript - 如何将参数传递给 Mongo 脚本

mongodb - 检查当前与 MongoDb 的连接数

node.js - TypeError : db. 集合不是函数

mongodb - 在同一数据库中复制集合的最快方法是什么?

mongodb - MongoDB 数据库中的数据如何存储在磁盘上?

node.js - 保持打开 MongoDB 数据库连接

javascript - 在 MongoDB 和 Mongoose 中执行全文搜索的最佳方法