How to Dynamically $set Field Name From Variable in Mongo Script

时间:2016-10-15 17:29:07

标签: javascript mongodb scripting

I'm working on a script that will run in the shell in MongoDB. I am only using pure Javascript not node.js or Meteor. I have an array that contains key and value pairs for field names and field values respectively. I'm trying to use the key value from the array as the field name in an update function.

var USER_ID = 1234567
var myArray = [
   { key : "name.first.nickname", value : "Sammy" }
]

for(var i = 0; i < myArray.length; i++){
    setFields(myArray[i].key, myArray[i].value)
}

function setFields(key, value){
    db.nameCollection.update(
    {user : USER_ID},
    {
     $set: {
       key : value
      }
    }
   )
}

The field name is always set to "key" instead of the key variable's value "name.first.nickname". Is there a way to do this?

1 个答案:

答案 0 :(得分:1)

function setFields(key, value){

    var update = {$set:{}};    
    update.$set[key] = value;

    db.Test.update(
    {userId : userId},
    update
   );
}

var userId = "daniele";

var myArray = [
   { key : "dynamic_key_002", value : "Sammy" }
]

for(var i = 0; i < myArray.length; i++){
    setFields(myArray[i].key, myArray[i].value)
}

此外 - 如果您需要进行大量更新,也许您可​​以考虑批量处理它们,而不是逐个进行查询。

MongoDB使客户端能够批量执行写入操作。批量写入操作会影响单个集合。 MongoDB允许应用程序确定批量写入操作所需的可接受的确认级别。

https://docs.mongodb.com/manual/core/bulk-write-operations/