$concatArrays運算子可用來將多個數組合並成單一陣列。 當您需要合併檔中不同檔或字段的陣列時,這個運算符很有用。
語法
{
$concatArrays: ["<array1>", "<array2>"]
}
參數
| 參數 | Description |
|---|---|
<array1>, <array2> |
以串連為目標的陣列欄位。 |
範例
請參考商店集合中的此範例檔。
{
"_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
},
{
"categoryName": "DJ Cables",
"totalSales": 1000
}
],
"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
}
]
},
{
"eventName": "Discount Delight Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 5,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 5,
"Day": 18
}
}
}
],
"tag": [
"#ShopLocal",
"#FashionStore",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}
範例 1:串連檔中的陣列
此查詢會 categoryName 將陣列中的 promotionEvents.discounts 欄位與陣列合併 tag 為單一 combinedTags 陣列。
db.stores.aggregate([{
$match: {
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}
}, {
$project: {
combinedTags: {
$concatArrays: ["$promotionEvents.discounts.categoryName", "$tag"]
}
}
}])
此查詢會傳回下列結果。
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"combinedTags": [ '#ShopLocal', '#NewArrival', '#NewArrival', '#FreeShipping' ]
}
]
相關內容
- 檢視從 MongoDB 遷移到 Azure DocumentDB 的選項。
- 閱讀有關 與 MongoDB 的功能相容性的更多資訊。