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

标签 javascript node.js mongodb mongoose

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"} 
        } 
    }} 
)

(我知道 $cond 用于聚合,我在这里用它作为我想到的示例。)

最佳答案

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.
            }
        )
    }
)

关于javascript - mongodb在文档更新期间使用if else设置字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30385663/

相关文章:

mongodb - 伯克利数据库 : how does it compare to MongoDB?

node.js - 使用相同的回调函数异步多个请求

javascript - 有什么方法可以检测 CSS 文件何时已完全加载?

javascript - Vue.js 和 Immutable.js

node.js - 子文档上的 Mongoose 虚拟字段

javascript - NodeJS - Controller 方法不调用

node.js - 构建 Node.js API(使用标准 MongoDB URI 的 mongodb 连接出现意外 token 错误)

javascript - 访问javascript对象中包含斜杠的属性名称

javascript - 如何使用 onstart 和 oncomplete 创建 jquery 函数

javascript - Mongoose 查找多个文档