Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a document field in mongo based on another field's value

Tags:

mongodb

Suppose I have two fields F1 and F2. I want to update F1 to become F1 + ", " + F2. Can I do so with a single update command in mongo?

like image 321
mark Avatar asked Apr 19 '12 12:04

mark


People also ask

How do you update a specific field in MongoDB?

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.

Which operator is used to update specific fields in MongoDB?

Use Update Operator Expressions ( $inc and $set ) The db. collection. update() method updates only the corresponding fields in the document.

Which update operator is used if you want to update the value of a field to 1/3rd of its original value?

In MongoDB, the $inc operator is used to increment the value of a field by a specified amount. The $inc operator adds as a new field when the specified field does not exist, and sets the field to the specified amount.

What does Upsert do 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

No, you can't do that. You can't use expressions in mongodb updates. The only way is to fetch this document to the client, compose new field value there and issue a prepared update statement.

like image 114
Sergio Tulentsev Avatar answered Nov 02 '22 15:11

Sergio Tulentsev