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

有没有办法在MongoDB中使用if / else在更新期间设置字段值。 我知道,我可以使用查找,返回文档,循环他们,如果/其他检查每一个做一个新的保存查询每个文件。

但是,这似乎是浪费,如果有一种方式有条件地更新一次。

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

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

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

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

将条件检查移到update查询select器中,然后使用{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. } ) } )