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/