database MongoDB 更新条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36698569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 08:01:45  来源:igfitidea点击:

MongoDB update with condition

mongodbdatabase

提问by q99

I'm trying to update some field in my collection depending on a condition.

我正在尝试根据条件更新我的集合中的某些字段。

I want to set field activeto trueif the condition is trueand to falseotherwise

我想设置字段activetrue如果条件truefalse以其他方式

This is update without condition

这是无条件更新

db.consent.update(
{}, //match all
{
    $set: {
        "active": true
    }
}, 
{
    multi: true,
}

)

I would like to add a condition to update like this:

我想添加一个条件来更新,如下所示:

db.consent.update(
{},
$cond: {
    if: {

        $eq: ["_id", ObjectId("5714ce0a4514ef3ef68677fd")]

    },
    then: {
        $set: {
            "active": true
        }
    },
    else: {
        $set: {
            "active": false
        }
    }
}, 
{
    multi: true,
}

)

)

According to https://docs.mongodb.org/manual/reference/operator/update-field/there is no $condoperator for update.

根据https://docs.mongodb.org/manual/reference/operator/update-field/没有$cond更新操作符。

What are my options here to execute this update as a single command?

我在这里有哪些选项可以作为单个命令执行此更新?

采纳答案by BanksySan

You can't.

你不能。

Mongo doesn't support combining fields, conditionals etc. in the update statement.

Mongo 不支持在更新语句中组合字段、条件等。

回答by Xavier Guihot

Starting Mongo 4.2, db.collection.update()can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:

开始Mongo 4.2db.collection.update()可以接受聚合管道,最后允许基于另一个字段更新/创建一个字段:

// { a: "Hello", b: "World" }
// { a: "Olleh", b: "Dlrow" }
db.collection.update(
  {},
  [ { $set: { active: { $eq: [ "$a", "Hello" ] } } } ],
  { multi: true }
)
// { a: "Hello", b: "World", active: true  }
// { a: "Olleh", b: "Dlrow", active: false }
  • The first part {}is the match query, filtering which documents to update (in our case all documents).

  • The second part [ { $set: { active: { $eq: [ "$a", "Hello" ] } } } ]is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $setis a new aggregation operator and an alias of $addFields. Then any aggregation operator can be used within the $setstage; in our case a conditional equality check on which depends the value to use for the new activefield.

  • Don't forget { multi: true }, otherwise only the first matching document will be updated.

  • 第一部分{}是匹配查询,过滤要更新的文档(在我们的例子中是所有文档)。

  • 第二部分[ { $set: { active: { $eq: [ "$a", "Hello" ] } } } ]是更新聚合管道(注意方括号表示使用聚合管道)。$set是一个新的聚合运算符,是 的别名$addFields。然后可以在$set阶段内使用任何聚合运算符;在我们的例子中,条件相等性检查取决于用于新active字段的值。

  • 不要忘记{ multi: true },否则只会更新第一个匹配的文档。

回答by Saleem

You can update MongoDB document conditionally using findAndModify()or findOneAndUpdate()if you have MongoDB version 3.2+

如果您有 MongoDB 3.2+ 版,您可以使用findAndModify()findOneAndUpdate()有条件地更新 MongoDB 文档

回答by Markos Evlogimenos

Of course you can.... by running 2 queries

当然你可以......通过运行2个查询

db.collection.update({condition}, { $set: { state } }, { multi: true });
db.collection.update({!condition}, { $set: { state } }, { multi: false });

for your example case

对于您的示例案例

db.consent.update(
  {"_id": ObjectId("5714ce0a4514ef3ef68677fd")},
  { $set: { "active": true } });

db.consent.update(
  {"_id": {$ne: ObjectId("5714ce0a4514ef3ef68677fd")}},
  { $set: { "active": false } },
  { multi: true });

回答by Hoiama Rodrigues

db.consent.update(
    {
       //YOUR CONDITIONAL HERE TO APLLAY UPDATE ONLY IF CONDITIONAL HAPPEN, SO THE "active": true WILL BE APPLY. 
    }, 
    {
       $set: {
         "active": true,
         "active2": FALSE,
       }
    }, 
    {
        multi: true,
    }
)