The mongodb parameter value sets the value if during document updating

Is there a way in mongodb to use if / else to set the field value during update. I know that I can use find, return documents, iterate over them and do it if / else check each and create a new save request for each of the documents.

However, this seems wasteful if there is a way to conditionally upgrade at a time.

Is it possible to conditionally set a field value, for example, like

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

(I know that $ condis is used for aggregation, I used it here as an example of what I mean.)

+4
source share
1 answer

MongoDB , . , , find, loop save.

update, ( ), {multi: true}, .

// 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.
            }
        )
    }
)
+3

Source: https://habr.com/ru/post/1589315/


All Articles