運算子 $arrayToObject 可用來將數位轉換成單一檔。 當您需要將索引鍵/值組的數位轉換成更結構化的檔案格式時,這個運算子很有用。
語法
{
$arrayToObject: "<array>"
}
參數
| 參數 | Description |
|---|---|
<array> |
要轉換成檔的陣列。 陣列中的每個元素都必須是:a) 兩個元素陣列,其中第一個專案是功能變數名稱,而第二個元素是域值。 b) 只有兩個字段 「k」 和 「v」 的檔,其中 「k」 是功能變數名稱,而 「v」 則是域值。 |
範例
請參考商店集合中的此範例檔。
{
"_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:將陣列轉換成索引鍵:值檔
此查詢會 salesByCategory 將陣列轉換成物件,其中每個 categoryName 都是索引鍵,且 totalSales 是對應的值。 此轉換會直接從物件結構依類別簡化銷售數據的存取。
db.stores.aggregate([{
$match: {
_id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}
},
{
$project: {
"sales.salesByCategory": {
$arrayToObject: {
$map: {
input: "$sales.salesByCategory",
as: "item",
in: {
k: "$$item.categoryName",
v: "$$item.totalSales"
}
}
}
}
}
}
])
查詢會傳回下列結果。
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"sales": {
"salesByCategory": {
"DJ Headphones": 35921,
"DJ Cables": 1000
}
}
}
]
相關內容
- 檢視從 MongoDB 遷移到 Azure DocumentDB 的選項。
- 閱讀有關 與 MongoDB 的功能相容性的更多資訊。