MongoDB更新条件 [英] MongoDB update with condition
问题描述
我正在尝试根据条件更新集合中的某些字段.
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屋!