Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables in MongoDB update statement

I am trying to use a variable as the field name in an update statement and it is not working at all, any suggestions?

for example:

COLLECTIONNAME.update(
    { _id: this._id },
    { $set: { VARIABLE1 : VARIABLE2 } }
);

actual code:

 'blur .editable' : function () {
      var target = event.currentTarget.value;
      var field = event.currentTarget.name;
      field = ' " ' + field + ' " ';
      Hostings.update( { _id: this._id },{ $set: { field : target } } );
    }
like image 227
glasses Avatar asked Aug 29 '13 06:08

glasses


People also ask

How do I update multiple values in MongoDB?

Update Multiple Fields of a Single Document. We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.

Why we use $$ in MongoDB?

MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array.

What is the difference between update and Upsert in MongoDB?

Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.


1 Answers

As per L. Norman's comment, I find using the [] for the field value works instead

collection = "my_collection"
db.getCollection(collection).find({}).forEach(function(doc) {
    var new_field = "new_field";
    var new_value = "new_value";

    db.getCollection(collection).update({_id: doc._id}, 
        {$set: {[new_field] : new_value}}) 
})
like image 95
Yi Xiang Chong Avatar answered Oct 07 '22 10:10

Yi Xiang Chong