Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a value in MongoDB based on its current value

Tags:

mongodb

I want to do something like this, but the this keyword doesn't seem to be set inside the update statement.

db.items.update({foo:…}, {$set: {bar: this.foo}}, false, true)

Do I have to use eval to accomplish this?

like image 698
dstrelau Avatar asked Mar 19 '10 19:03

dstrelau


People also ask

Is it possible to update MongoDB field using value of another field?

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.

How we can update the particular data in MongoDB explain with an example?

MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.

What is Upsert in MongoDB?

In MongoDB, upsert is a method that is used to insert and update the value in any operation. In other words, the MongoDB upsert method is a combination of insert and update (insert + update = upsert). By default, the upsert method's value is always false.


1 Answers

Yes, you can't refer to other fields in the modifier. You'll have to use db.eval.

like image 192
kristina Avatar answered Oct 16 '22 00:10

kristina