{
FullName: "Emily Clark",
Details: {
Income: [
{
2021: [
{
time: "Sun Apr 11 2021 17:42:39 GMT 0530 (India Standard Time)",
description: "Web",
amount: "3700",
},
{
time: "Sun May 21 2022 07:12:59 GMT 0530 (India Standard Time)",
description: "Pc Monitor",
amount: "45000",
},
],
},
{
2022: [
{
time: "Sat May 28 2022 12:23:34 GMT 0530 (India Standard Time)",
description: "Class",
amount: "4100",
},
],
},
],
Expense: [
{
2022: [
{
time: "Tue May 17 2022 20:30:39 GMT 0530 (India Standard Time)",
descritption: "Car Wash",
amount: 4000,
},
{
time: "Fri May 19 2022 10:23:29 GMT 0530 (India Standard Time)",
description: "Loundry",
amount: "300",
},
],
},
],
},
};
在這里,我首先添加了一個新的 Expense Data 物件,Details.Income.0.2021因此它在 Income 之后創建了一個新的陣列和物件,但是在為新的 Year 2022 添加新的 Expense 資料后,它被添加到了第一個 income 元素的現有物件中,如何創建一個僅當年份不存在時才用于新年的新陣列物件?
第二個收入元素是我從 MongoDB shell 手動添加的。
如果存在年份,我希望資料看起來像Expense同一年份的兩個物件資料。
我知道這個解釋有點混亂,但如果需要,我愿意提供更多資訊。
uj5u.com熱心網友回復:
編輯: 由于Income和Expense是物件陣列,并且每年都是其中的關鍵,因此所有解決方案都相當復雜。
一種選擇是執行以下操作:
- 將新專案添加到檔案中,
- 計算
lastYear上Income lastYear如果與輸入年份不同,則添加新年份yearString- 洗掉最后一年
Details.Income以對其進行編輯。保持為last. - 將新專案添加到其中。
- 將其合并回原始結構。
db.collection.update({
FullName: "Emily Clark"
},
[
{$addFields: {
newItem: {a: "test"},
year: yearString
}
},
{
$addFields: {
lastYear: {
$reduce: {
input: {$objectToArray: {$last: "$Details.Income"}},
initialValue: "",
in: {$concat: ["$$value", "$$this.k"]}
}
}
}
},
{
$addFields: {
newArr: {
$cond: [
{$eq: ["$lastYear", "$year"]},
[],
[{yearString: []}]
]
}
}
},
{
$set: {
"Details.Income": {
$concatArrays: ["$Details.Income", "$newArr"]
},
year: "$$REMOVE",
newArr: "$$REMOVE"
}
},
{
$set: {
last: {$objectToArray: {$last: "$Details.Income"}},
"Details.Income": {
$slice: ["$Details.Income", {$subtract: [{$size: "$Details.Income"}, 1]
}
]
}
}
},
{
$set: {
last: {
$map: {
input: "$last",
as: "item",
in: {
v: {$concatArrays: ["$$item.v", ["$newItem"]]},
k: "$$item.k"
}
}
}
}
},
{$set: {last: {$arrayToObject: ["$last"]}}},
{
$set: {
"Details.Income": {$concatArrays: ["$Details.Income", ["$last"]]},
last: "$$REMOVE",
newItem: "$$REMOVE",
lastYear: "$$REMOVE"
}
}
])
游樂場示例
如果Income并且Expense是一個物件而不是物件陣列,它將很簡單:
db.collection.update({
FullName: "Emily Clark"
},
{
$push: {
"Details.Expense.2022":
{
time: "Fri May 19 2022 10:23:29 GMT 0530 (India Standard Time)",
description: "Loundry",
amount: "300",
}
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/482844.html
