如何更新已知索引值的Node.js + Mongodb中的嵌套数组

时间:2014-12-18 09:55:43

标签: node.js mongodb

我想更新Mongo DB中的嵌套数组(使用Node.js)。我能够获得数组索引位置。

我如何更新?我在$set

中使用转义字符时遇到了一些问题

这是我正在做的事情:

testCollection.update({
        "uniqueID": someID,
        "topLevelObject.innerObjectValue": innerObjectVal
    }, {
        $set: {

            'array.' + outerArrayIndex + '.value': updatedValue,

        }

    }, function(err, result) {

        if (err) {
            console.log("Error occurred while updating db info");
        }

    }
);

1 个答案:

答案 0 :(得分:2)

很难说出问题是什么,因为您没有包含示例文档或显示错误消息或出现了什么问题。假设您的文档看起来像

{
    "_id" : 0,
    "array" : [{ "value" : 2 }, { "value" : 6 }]
}

然后您的上述查询应该有效,例如

db.test.update({ "_id" : 0 }, { "$set" : { "array.1.value" : 906 } })

将文档修改为

{
    "_id" : 0,
    "array" : [{ "value" : 2 }, { "value" : 906 }]
}

我省略了其他查询条件,因为没有必要指定唯一ID - 可能条件不匹配任何文档?

如果您的文档看起来像

{
    "_id" : 0,
    "array" : [2, 6]
}

然后您在更新查询中不需要.value

db.test.update({ "_id" : 0 }, { "$set" : { "array.1" : 906 } })

我还要检查变量outerArrayIndex的字符串连接是否产生了正确的字段路径。