我有一個包含物件元素的陣列屬性的檔案。
例如
{
"_id": "61c01098bc29520008efc00f",
"name": "codedump",
"employments": [
{
"type": "PERMANENT",
"salary": 1000000000
},
{
"type": "TEMP",
"salary": 1000000000
},
{
"type": "PART_TIME",
"salary": 1000000000
},
]
}
在更新就業工資時,type如果型別已經在就業中,那么我需要更新salary唯一的。否則我需要將新專案推送到陣列。我試圖找到一種方法來在單個查詢中完成這項作業。
- 如果該型別已存在于陣列中(用于更新):
/// Update data:
{
"type": "PERMANENT",
"salary": 10
}
// For this case I want the example document to become:
{
"_id": "61c01098bc29520008efc00f",
"name": "codedump",
"employments": [
{
"type": "PERMANENT",
"salary": 10 // From 1000000000 to 10
},
{
"type": "TEMP",
"salary": 1000000000
},
{
"type": "PART_TIME",
"salary": 1000000000
},
]
}
- 如果型別不存在:
/// Update data:
{
"type": "INVESTMENT",
"salary": 10000
}
// For this case I want the example document to become:
{
"_id": "61c01098bc29520008efc00f",
"name": "codedump",
"employments": [
{
"type": "PERMANENT",
"salary": 1000000000
},
{
"type": "TEMP",
"salary": 1000000000
},
{
"type": "PART_TIME",
"salary": 1000000000
},
{
"type": "INVESTMENT",
"salary": 10000
}
]
}
uj5u.com熱心網友回復:
從技術上講,1 次呼叫是可行的,從 Mongo v4.2 開始,您可以使用流水線更新,這基本上允許您在更新主體中使用聚合運算子,因此您幾乎可以實作任何目標。
我會說但是它絕對不是很有效,它實際上取決于您想要最大化/最小化系統的哪個部分(網路/資料庫負載/等)。
你可以這樣做:
const input = {
"type": "INVESTMENT",
"salary": 10000
}
db.collection.update({},
[
{
$set: {
employments: {
$cond: [
{
$in: [
input.type,
"$employments.type"
]
},
{
$map: {
input: "$employments",
in: {
$cond: [
{
$eq: [
"$$this.type",
input.type,
]
},
{
type: "$$this.type",
salary: input.salary
},
"$$this"
]
}
}
},
{
$concatArrays: [
"$employments",
[
input
]
]
}
]
}
}
}
])
蒙戈游樂場
uj5u.com熱心網友回復:
我不知道您想要的東西是否可以在一次操作中實作...
話雖如此,我將如何做,使用$位置運算子來更新我想要的陣列元素。檔案和操場。
db.collection.update({
"employments.type": "PERMANENT",
},
{
"$set": {
"employments.$.salary": 10
}
},
{
"multi": false,
"upsert": false
})
此操作僅在元素存在于陣列中時才有效。如果不是,操作將失敗。然后,您可以在代碼中捕獲例外并使用$push. 操場
db.collection.update({},
{
"$push": {
"employments": [
{
"type": "INVESTMENT",
"salary": 10000
}
]
}
},
{
"multi": false,
"upsert": false
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399229.html
標籤:节点.js 数组 MongoDB aws-lambda mongodb-查询
上一篇:驗證檔案是否與我發送的資料相同
下一篇:MongoDB聚合中的總計
