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

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

问题描述

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

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

这是无条件更新

db.consent.update({},//匹配所有{$set:{活动":真实}},{多:真实,})

我想添加一个条件来更新:

db.consent.update({},$cond: {如果: {$eq: ["_id", ObjectId("5714ce0a4514ef3ef68677fd")]},然后: {$set:{活动":真实}},别的: {$set:{活动":假}}},{多:真实,}

)

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

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

解决方案

你不能.

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


请参阅下面的https://stackoverflow.com/a/56551655/442351.

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

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

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 $cond operator for update.

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

解决方案

You can't.

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


See https://stackoverflow.com/a/56551655/442351 below.

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

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