在mongodb中是否有办法在更新期间使用if / else设置字段值。 i知道我可以使用find,返回文档,循环遍历它们,并对每个文件执行if / else检查,并为每个文档创建一个新的保存查询。
Is there a way in mongodb to use if/else to set a field value during an update. i know that i can use find, to return documents, loop over them, and do if/else check on each and make a new save query for each of the documents.
然而,如果有办法一次性有条件地更新,这似乎很浪费。
However, that seems wasteful, if there is a way to update conditionally in one go.
是否可以有条件地设置字段值,例如像这样
Is it possible to conditionally set a field value, e.g like this
Documents.update( {some_condition: true}, {$set: {"status": {$cond: {if : {"some field": "some condition"}}, {then: "value 1"} , {else: "value 2"} } }} )(我知道$ condis用于聚合,我在这里用它作为我想到的一个例子。)
(I know that $condis used for aggregation, i used it here as an example of what i have in mind.)
推荐答案MongoDB不支持您正在寻找的那种条件更新。但是,您仍然可以比使用查找,循环和保存方法做得更好。
MongoDB doesn't support the sort of conditional update you're looking for. However, you can still do better than using a find, loop, and save approach.
将条件检查移动到更新查询选择器然后发出两个更新(每种情况一个),使用 {multi:true} 将更新应用于所有匹配的文档。
Move the condition check into the update query selector and then issue two updates (one for each case), using {multi: true} to apply the update to all matched docs.
// 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. } ) } )更多推荐
mongodb在文档更新期间使用if else设置字段值
发布评论