如何使用 javascript var 引用 Mongo 数据库集合的字段

How to use the javascript var to reference the Mongo DB collection's field

我想将字段 value 类型从字符串更改为对象。

...{value: "my title"}... ===> ...{value:{value:"my title ABC"}}

在 Mongo shell 中,我通过 JavaScript var articlePath 显示此字段。现在,如何使用此 var 来更新字段值?

下面的代码是创建一个新字段 articlePath 而不是使用 var 的值。

var articlePath = "layout.content.header." + i + "." + j + ".value"
var articleValue = block.value + " ABC"
db.mycollection.update(
    {_id: catId},
    {
        $set: {
            articlePath: {value: articleValue}
        }
    },
    function(err, numberUpdated) {
        print("--->err: ", err)
    }
)

试试下面的代码片段

var articlePath = {};
var keyName = "layout.content.header." + i + "." + j + ".value";
var articleValue = block.value + " ABC";
articlePath[keyName] = articleValue;

db.mycollection.update(
    {_id: catId},
    {
        $set: articlePath
    },
    function(err, numberUpdated) {
        print("--->err: ", err)
    }
)

谢谢

您不能使用文字表示法通过变量值设置键名。试试这个方法:

var update = { "$set" : { } }
update["$set"][articlePath] = { "value" : articleValue }
db.mycollection.update({ "_id" : catId }, update, *callback*)