我在 NodeJS 上使用貓鼬 v5.13
對于我知道 id 的檔案
{
_id: ...,
edible: 'fruit'
}
我想要update這個檔案并執行此操作
if (obj.edible == 'fruit') {
obj.edible = 'apple';
} else if(obj.edible == 'vegetable') {
obj.edible = 'carrot';
}
但這需要我先找到然后更新,因此,兩個查詢,我的問題是我可以在一個操作中完成
uj5u.com熱心網友回復:
db.collection.update(
{
_id: ObjectId("61723c7378b6d3a5a02d908e")
},
[
{
$set: {
edible: {
$switch: {
branches: [
{ case: { $eq: [ "$edible", 'fruit' ] }, then: "apple" },
{ case: { $eq: [ "$edible", 'vegetable' ] }, then: "carrot" }
],
default: "$edible"
}
}
}
}
])
在這里測驗
uj5u.com熱心網友回復:
詢問
- 管道更新需要 >= MongoDB 4.2
- 你只有 2 個案例,你也可以使用
$cond,但我使用了$switch所以你可以在需要時添加更多
測驗代碼在這里
db.collection.update({
"_id": 1
},
[
{
"$set": {
"edible": {
"$switch": {
"branches": [
{
"case": {
"$eq": [
"$edible",
"fruit"
]
},
"then": "apple"
},
{
"case": {
"$eq": [
"$edible",
"vegetable"
]
},
"then": "carrot"
}
],
"default": "unknown"
}
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/333822.html
上一篇:好友函式不能訪問私有成員
