匯總 $replaceWith 階段運算子可用來將輸入檔取代為指定的檔。 運算子 $replaceWith 會將檔從一個結構轉換成另一個結構,或將檔完全取代為新的欄位和值。
語法
{
"$replaceWith": <newDocument>
}
參數
| 參數 | Description |
|---|---|
newDocument |
要取代原始文件的新文件 |
範例
請參考商店集合中的此範例檔。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
範例 1 - 回傳文件,將源文件的內容替換為項目子集
首先,透過_id欄位匹配特定文件,並用指定的欄位替換文件的內容。
db.stores.aggregate([{
$match: {
_id: "bda56164-954d-4f47-a230-ecf64b317b43"
}
}, {
$replaceWith: {
_id: "$_id",
name: "$name",
sales: "$sales.totalSales"
}
}])
此查詢會傳回下列結果:
[
{
"_id": "bda56164-954d-4f47-a230-ecf64b317b43",
"name": "Boulder Innovations | Home Security Place - Ankundingburgh",
"sales": 37015
}
]
範例 2 - 傳回在匯總指定字段之後取代源文件內容的檔
db.stores.aggregate([{
$match: {
_id: "bda56164-954d-4f47-a230-ecf64b317b43"
}
}, {
$replaceWith: {
_id: "$_id",
name: "$name",
totalStaff: {
$add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"]
}
}
}])
這會傳回下列結果:
[
{
"_id": "bda56164-954d-4f47-a230-ecf64b317b43",
"name": "Boulder Innovations | Home Security Place - Ankundingburgh",
"totalStaff": 29
}
]