$merge匯總管線中的階段是用來將匯總查詢的結果寫入指定的集合中。 此階段特別適用於根據匯總作業輸出,更新或插入檔至目標集合等工作。 在單一作業中結合數據轉換和數據持續性,有助於簡化工作流程。
語法
{
$merge: {
into: <collection>,
on: <field or fields>,
whenMatched: <action>,
whenNotMatched: <action>
}
}
參數
| 參數 | Description |
|---|---|
into |
指定將寫入匯總結果的目標集合。 |
on |
指定欄位,以識別目標集合中的相符檔。 |
whenMatched |
指定找到相符檔時要採取的動作。 選項包括 merge、 replace、 keepExisting、 fail或自定義管線。 |
whenNotMatched |
指定找不到相符檔時要採取的動作。 選項包括 insert 或 discard。 |
範例
請參考商店集合中的此範例檔。
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"staff": {
"totalStaff": {
"fullTime": 2,
"partTime": 0
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35921
}
],
"fullSales": 3700
},
"promotionEvents": [
{
"eventName": "Bargain Blitz Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 3,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 2,
"Day": 18
}
},
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
}
],
"tag": [
"#ShopLocal",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}
範例 1:將數據合併至集合
此查詢會彙總文件,並將結果寫入名為 salesSummary的集合,更新相符的 _id 現有文件,並插入新文件。
db.sales.aggregate([
{
$group: {
_id: "$sales.salesByCategory.categoryName",
totalSales: { $sum: "$sales.salesByCategory.totalSales" }
}
},
{
$merge: {
into: "salesSummary",
on: "_id",
whenMatched: "merge",
whenNotMatched: "insert"
}
}
])
範例 2:取代目標集合中的檔
本範例會根據 promotionEventsSummary 欄位取代集合中的_id檔。
db.promotionEvents.aggregate([
{
$project: {
_id: "$eventName",
startDate: "$promotionalDates.startDate",
endDate: "$promotionalDates.endDate",
totalDiscounts: { $size: "$discounts" }
}
},
{
$merge: {
into: "promotionEventsSummary",
on: "_id",
whenMatched: "replace",
whenNotMatched: "insert"
}
}
])