Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb: updating a variable field name

I want to add a new field with a variable name to an object in the DB : meaning, I don't know the name of the field, but it's held in a variable "newFieldName".

So what I want to do is basically this:

var newFieldName = "world";
db.bios.update(
   { _id: 3 },
   { $set: {
             "hello."+newFieldName: "Amazing Grace"
           }
   }
)

After the update, I expect the object "hello" to have a field "world" with the value "Amazing Grace".

but this doesn't even compile, let alone work. How can I do it?

like image 451
Yossale Avatar asked Dec 02 '13 11:12

Yossale


Video Answer


3 Answers

You can use an intermediary object:

var update = { $set : {} };
update.$set['hello.' + newFieldName] = 'Amazing Grace';
db.bios.update({ _id : 3 }, update, ...)
like image 51
robertklep Avatar answered Oct 11 '22 18:10

robertklep


var some_object = Posts.findOne({...});
var new_value = 1337;

Posts.update(another_object._id,
    {$set: {
        [some_object.some_field]:new_value,
        }
    }
);
like image 4
Andy Avatar answered Oct 11 '22 18:10

Andy


To answer @yossale & @robertklep, the inline version is in fact possible using an expression and the comma operator:

var newFieldName = "world", o;
db.bios.update(
   { _id: 3 },
   {$set:(o = {}, o["hello."+newFieldName] = "Amazing Grace", o)}
)
like image 3
FGRibreau Avatar answered Oct 11 '22 19:10

FGRibreau