如何将查找和更新合并为 1 个更新
How to combine find and update to 1 update
我正在使用 Spring Data MongoTemplate,试图优化 mongodb 更新。我可以 只有 1 个更新 而没有 find()
首先检查数据库中文档的 status
吗:
- 如果状态不是“已阻止”,请更新状态并添加到
动作。
- 如果状态为“已阻止”,只需添加操作,而不是更新状态。
Java object to update:
status: "Display",
action: "Show"
mongodb:
{
status: "Blocked",
actions: [
"Show",
"Hide",
"Show",
...
]
}
您可以使用聚合管道进行更新。在 $addFields
阶段对状态字段进行条件检查。
db.collection.update({},
[
{
"$addFields": {
"userInput": {
status: "Display",
action: "Show"
}
}
},
{
"$addFields": {
"status": {
"$cond": {
"if": {
$ne: [
"$status",
"Blocked"
]
},
"then": "$userInput.status",
"else": "Blocked"
}
},
actions: {
"$concatArrays": [
[
"$userInput.action"
],
"$actions"
]
}
}
},
{
"$unset": "userInput"
}
],
{
multi: true
})
这里是Mongo playground供您参考。
我正在使用 Spring Data MongoTemplate,试图优化 mongodb 更新。我可以 只有 1 个更新 而没有 find()
首先检查数据库中文档的 status
吗:
- 如果状态不是“已阻止”,请更新状态并添加到 动作。
- 如果状态为“已阻止”,只需添加操作,而不是更新状态。
Java object to update:
status: "Display",
action: "Show"
mongodb:
{
status: "Blocked",
actions: [
"Show",
"Hide",
"Show",
...
]
}
您可以使用聚合管道进行更新。在 $addFields
阶段对状态字段进行条件检查。
db.collection.update({},
[
{
"$addFields": {
"userInput": {
status: "Display",
action: "Show"
}
}
},
{
"$addFields": {
"status": {
"$cond": {
"if": {
$ne: [
"$status",
"Blocked"
]
},
"then": "$userInput.status",
"else": "Blocked"
}
},
actions: {
"$concatArrays": [
[
"$userInput.action"
],
"$actions"
]
}
}
},
{
"$unset": "userInput"
}
],
{
multi: true
})
这里是Mongo playground供您参考。