mongodb在文档更新期间使用if else设置字段值

Rai*_*mer 6 javascript mongoose mongodb node.js

在mongodb中是否有一种方法可以在更新期间使用if/else设置字段值.我知道我可以使用find,返回文档,循环遍历它们,并对每个文档执行if/else检查并为每个文档创建一个新的保存查询.

但是,如果有一种方法可以一次性有条件地更新,那么这似乎很浪费.

是否可以有条件地设置字段值,例如像这样

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

(我知道$ condis用于聚合,我在这里用它作为我想到的一个例子.)

Alp*_*til 6

答案:是的

在聚合管道中使用$set阶段几乎是可能的

  1. 使用 $set 计算每条记录中的条件值
  2. 使用$out更新集合中的记录

例子:

db.collectionname.aggregate(
    [
        {
            $set: {                   //Compute the new value
                'ResultField': {
                    $cond: {
                        if: {
                            $lt: ['$ScoreField', 40]
                        },
                        then: "Fail",
                        else: "Pass"
                    }
                }
            }
        },
        {
            $out: 'collectionname'    //Update the records in collection
        }
    ]
)
Run Code Online (Sandbox Code Playgroud)


Joh*_*yHK 5

MongoDB不支持您要查找的条件更新。但是,您仍然可以比使用查找,循环和保存方法做得更好。

将条件检查移到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.
            }
        )
    }
)
Run Code Online (Sandbox Code Playgroud)