Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb set field value using if else during document update

Is there a way in mongodb to use if/else to set a field value during an update. i know that i can use find, to return documents, loop over them, and do if/else check on each and make a new save query for each of the documents.

However, that seems wasteful, if there is a way to update conditionally in one go.

Is it possible to conditionally set a field value, e.g like this

Documents.update(
    {some_condition: true}, 
    {$set: {"status": 
        {$cond: 
              {if  : {"some field": "some condition"}},
              {then:  "value 1"} ,
              {else: "value 2"} 
        } 
    }} 
)

(I know that $cond is used for aggregation, i used it here as an example of what i have in mind.)

like image 860
Rainer Plumer Avatar asked May 21 '15 22:05

Rainer Plumer


People also ask

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.

Which option should be used to update all the documents with the specified condition in the MongoDB query?

By default, the db. collection. update() method updates a single document. Include the option multi: true to update all documents that match the query criteria.

Which operator is used to update specific fields in MongoDB?

Comparing values (or numbers) using $max operator: Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 40000.


1 Answers

MongoDB doesn't support the sort of conditional update you're looking for. However, you can still do better than using a find, loop, and save approach.

Move the condition check into the update query selector and then issue two updates (one for each case), using {multi: true} to apply the update to all matched docs.

// Start with the "if" update
Documents.update(
    {some_condition: true, "some field": "some condition"}, 
    {$set: {"status": "value 1"}},
    {multi: true},
    function(err, numAffected) {
        // Now do the "else" update, using $ne to select the rest of the docs
        Documents.update(
            {some_condition: true, "some field": {$ne: "some condition"}}, 
            {$set: {"status": "value 2"}},
            {multi: true},
            function(err, numAffected) {
                // All done.
            }
        )
    }
)
like image 177
JohnnyHK Avatar answered Sep 21 '22 21:09

JohnnyHK