我正在尝试根据条件更新我的收藏中的某些字段.
我想设置字段active
,true
如果条件是true
和false
否则
这是无条件更新
db.consent.update(
{}, //match all
{
$set: {
"active": true
}
},
{
multi: true,
}
)
Run Code Online (Sandbox Code Playgroud)
我想添加一个更新的条件,如下所示:
db.consent.update(
{},
$cond: {
if: {
$eq: ["_id", ObjectId("5714ce0a4514ef3ef68677fd")]
},
then: {
$set: {
"active": true
}
},
else: {
$set: {
"active": false
}
}
},
{
multi: true,
}
Run Code Online (Sandbox Code Playgroud)
)
根据https://docs.mongodb.org/manual/reference/operator/update-field/,没有$cond
运营商进行更新.
我有什么选择将此更新作为单个命令执行?
Sal*_*eem 11
如果你有MongoDB版本3.2+,可以使用findAndModify()或findOneAndUpdate()有条件地更新MongoDB文档
开始于Mongo 4.2
,db.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 }
Run Code Online (Sandbox Code Playgroud)
第一部分{}
是匹配查询,过滤要更新的文档(在本例中为所有文档)。
第二部分[ { $set: { active: { $eq: [ "$a", "Hello" ] } } } ]
是更新聚合管道(请注意方括号表示使用聚合管道)。$set
是新的聚合运算符,别名为$addFields
。然后,可以在该$set
阶段内使用任何聚合运算符;在我们的例子中,条件相等性检查取决于要用于新active
字段的值。
不要忘记{ multi: true }
,否则只会更新第一个匹配的文档。
小智 7
我们可以使用聚合管道来做到这一点。在这里,我将男性更新为女性,将女性更新为男性。
db.customer.updateMany(
{ },
[
{ $set: { gender: { $switch: {
branches: [
{ case: { $eq: [ "$gender", 'male' ] }, then: "female" },
{ case: { $eq: [ "$gender", 'female' ] }, then: "male" }
],
default: ""
} } } }
]
)
Run Code Online (Sandbox Code Playgroud)
当然你可以......通过运行2个查询
db.collection.update({condition}, { $set: { state } }, { multi: true });
db.collection.update({!condition}, { $set: { state } }, { multi: false });
Run Code Online (Sandbox Code Playgroud)
对于您的示例案例
db.consent.update(
{"_id": ObjectId("5714ce0a4514ef3ef68677fd")},
{ $set: { "active": true } });
db.consent.update(
{"_id": {$ne: ObjectId("5714ce0a4514ef3ef68677fd")}},
{ $set: { "active": false } },
{ multi: true });
Run Code Online (Sandbox Code Playgroud)
小智 5
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,
}
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20586 次 |
最近记录: |