MongoDB更新条件 [英] MongoDB update with condition

查看:66
本文介绍了MongoDB更新条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果条件为true,我想将字段active设置为true,否则将其设置为false

I want to set field active to true if the condition is true and to false otherwise

这是无条件的更新

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,
}

)

根据 https://docs.mongodb.org/manual/reference /operator/update-field/没有用于更新的$cond运算符.

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

在这里,作为单个命令执行此更新有什么选择?

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

推荐答案

您不能.

Mongo不支持在update语句中组合字段,条件等.

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

这篇关于MongoDB更新条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆