jdub7 jdub7 - 1 month ago 12
Javascript Question

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

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?

Answer
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)
}

Also - if you need to make a lot of update, maybe you can consider to bulk them instead of making query one-by-one.

MongoDB provides clients the ability to perform write operations in bulk. Bulk write operations affect a single collection. MongoDB allows applications to determine the acceptable level of acknowledgement required for bulk write operations.

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

Comments