所以我想要在 $set 中做的是檢查該欄位是否存在,然后更新該值,但前提是該欄位存在。$cond 非常接近我想要實作的目標,但問題是我無法阻止它創建該欄位。
我可以過濾以僅獲取現有欄位,但在這種情況下,我必須逐個欄位而不是同時更新所有欄位,這將花費很長時間。
const data = await connection.collection("snapshot").updateMany({}, [
{
$set: {
field1: {
$cond: [
{ field1: { $exists: true } },
{ field1: "newValue" },
undefined, // do nothing
],
},
field2: {
$cond: [
{ field2: { $exists: true } },
{ field2: "newValue" },
undefined, // do nothing
],
},
field3: {
$cond: [
{ field3: { $exists: true } },
{ field3: "newValue" },
undefined, // do nothing
],
},
},
},
]);
我錯過了什么還是不可能做到?
我正在使用 mongo 5.0
uj5u.com熱心網友回復:
運算子$exists僅適用于find,不適用于聚合管道。檢查“欄位存在”并非易事,請參閱Or with If and In mongodb
我假設你喜歡更新檔案{ field3: "newValue" },你的更新就可以了{ field3: { field3: "newValue" } }
總之就是這個:
connection.collection("snapshot").updateMany({}, [
{
$set: {
field1: {
$cond: [
{ $ne: [{ $type: "$field1" }, "missing"] },
"newValue",
"$$REMOVE" // do nothing
]
},
field2: {
$cond: [
{ $ne: [{ $type: "$field2" }, "missing"] },
"newValue",
"$$REMOVE" // do nothing
]
},
field3: {
$cond: [
{ $ne: [{ $type: "$field3" }, "missing"] },
"newValue",
"$$REMOVE" // do nothing
]
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447312.html
