Mongodb:更新变量字段名称

Yos*_*ale 3 mongodb node.js

我想为DB中的对象添加一个带有变量名的新字段:意思是,我不知道该字段的名称,但它保存在变量"newFieldName"中.

所以我想要做的基本上是这样的:

var newFieldName = "world";
db.bios.update(
   { _id: 3 },
   { $set: {
             "hello."+newFieldName: "Amazing Grace"
           }
   }
)
Run Code Online (Sandbox Code Playgroud)

在更新之后,我希望对象"hello"具有值为"Amazing Grace"的字段"world".

但这甚至没有编译,更不用说工作了.我该怎么做?

rob*_*lep 12

您可以使用中间对象:

var update = { $set : {} };
update.$set['hello.' + newFieldName] = 'Amazing Grace';
db.bios.update({ _id : 3 }, update, ...)
Run Code Online (Sandbox Code Playgroud)