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 },
Solution 1:
You can do it this way:
'blur .editable' : function () {
var target = event.currentTarget.value;
var field = event.currentTarget.name;
var obj = {};
obj[field] = target;
Hostings.update( { _id: this._id },{ $set: obj } );
}
Javascrip objects can be accessed two ways:
object.attribute
or
object["attribute"]
if you use the second method you can access it with a variable
Solution 2:
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}})
})
Solution 3:
for your query
COLLECTIONNAME.update( { _id: this._id },{ $set: { VARIABLE1 : VARIABLE2 } } );
mongodb will take value of VARIABLE2 but it will consider "VARIABLE1" to be a field in the document.
For passing a variable whose value is a field name:
you will have to create a javascript object and use it as follows:
var obj={};
obj[VARIABLE1] = VARIABLE2; //where VARIABLE1 and VARIABLE2 are getting values from elsewhere earlier
If you want to have multiple fields this way, just add it to the same object:
obj[VARIABLE3]= VARIABLE4;
Then do update operation as:
db.collectionname.update( { _id: this._id },{ $set: obj } );
Post a Comment for "Using Variables In Mongodb Update Statement"