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

编程入门 行业动态 更新时间:2024-10-11 03:22:35
本文介绍了mongodb在文档更新期间使用if else设置字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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设置字段值

本文发布于:2023-11-24 11:48:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625081.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   文档   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!