nickponline
nickponline

Reputation: 25914

How do you update a field value in Mongo to equal another field's value in the same document?

I have some documents:

{"required" : 100, "total" : 30}

and I want to update the documents such that required = total (whatever the value of total is). I have tried:

db.collection.update({}, {"$set" : {"required" : "total"}})

but this sets it to the string literal "total", how do I access the value of the field, in this case 30.

Upvotes: 3

Views: 1088

Answers (1)

Trang Tung Nguyen
Trang Tung Nguyen

Reputation: 346

You can't do that. Try this instead:

db.collection.find().forEach(function(d) {
    d.required = d.total;
    db.collection.save(d);
});

Upvotes: 2

Related Questions