1

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 Answer 1

4
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/

Sign up to request clarification or add additional context in comments.

3 Comments

It worked! Thank you so much for answering that. I tried making an object that would have all of these key/value pairs and then pass that object to a function that does the update with $set so I'd only have to $set once to do the update. The key always ended up like objectName.name.first.nickname : "Sammy". How would you go about adding all the key/values in an object and then doing the $set with the key/values from the object without the object name in the keys?
I ended up finding out how to do the setFields function with an object instead of doing it field by field. It did it by:
function setFields(object){ var update = {$set: {} } for(var key in object){ var value = object[key] update.$set[key] = value }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.