[英]How to access nested array of objects in mongodb aggregation pipeline?
[英]How to convert array of objects into nested object in MongoDB aggregation pipeline
我目前正在做一個我的數據庫管理系統是 MongoDB 的項目。 我正在編寫一個聚合管道,其中有幾個階段。 我目前正在某個特定階段苦苦掙扎,我想獲得以下輸出。 MongoDB 有如此多的運算符表達式,我對使用哪一個來實現這一點感到困惑。 我有一個名為 Styles 和 Sku 的集合,如下所示:
// Schema for styles
const styles = mongoose.Schema({
id: Number,
productId: Number,
name: String,
sale_price: String,
original_price: String,
default_price: Boolean,
}, {
strict: false,
});
// Schema for skus
const skus = mongoose.Schema({
id: Number,
styleId: Number,
size: String,
quantity: String,
}, {
strict: false,
});
每種樣式都可以有多個 SKU,一對多關系。 在我的聚合管道中,我使用 $lookup 查找該特定樣式的所有 SKU,並在樣式文檔中添加一個名為 SKU 的新字段。 在 $lookup 之后我得到了這樣的結果。
{
"style_id": 1,
"name": "Forest Green & Black",
"original_price": "140",
"sale_price": "0",
"default?": true,
"skus": [
{
"id": 37,
"styleId": 1,
"size": "XS",
"quantity": 16
},
{
"id": 38,
"styleId": 1,
"size": "S",
"quantity": 8
}
]
}
這是預期的 $lookup 返回匹配的數組。 但我希望我的樣式文檔看起來像這樣。
{
"style_id": 1,
"name": "Forest Green & Black",
"original_price": "140",
"sale_price": "0",
"default?": true,
"skus": {
"37": {
"styleId": 1,
"size": "XS",
"quantity": 16
},
"38": {
"styleId": 1,
"size": "S",
"quantity": 8
}
}
}
有人可以知道如何在聚合管道中構造上述數據嗎? 任何幫助將不勝感激。 提前致謝。
您可以使用$map
或$reduce
將數組中的對象轉換為表單
[
{
k: <key1>
v: <value1>
},
{
k: <key2>
v: <value2>
}
]
然后使用$arrayToObject
將數組轉換為一個對象,如:
{
<key1>: <value1>,
<key2>: <value2>
}
總之,這可能看起來像:
{$addFields: {
skus: {
$arrayToObject: {
$map: {
input: "$skus",
in: {
k: {$toString: "$$this.id"},
v: "$$this"
}
}
}
}
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.