[英]How to convert array of objects into nested object in MongoDB aggregation pipeline
I am currently doing a project where my Database Management System is MongoDB.我目前正在做一个我的数据库管理系统是 MongoDB 的项目。 I am writing an aggregation pipeline where there are several stages.
我正在编写一个聚合管道,其中有几个阶段。 I am currently struggling at a particular stage where I want to obtain the following output.
我目前正在某个特定阶段苦苦挣扎,我想获得以下输出。 MongoDB has so many operator expressions that I am confused about which one to use to achieve this.
MongoDB 有如此多的运算符表达式,我对使用哪一个来实现这一点感到困惑。 I have a collection called Styles and Skus which are as follows:
我有一个名为 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,
});
Each style can have several SKUs, one-to-many relationships.每种样式都可以有多个 SKU,一对多关系。 In my aggregation pipeline, I am using $lookup to find all the SKUs of that particular style and adding a new field called SKUs in the styles document.
在我的聚合管道中,我使用 $lookup 查找该特定样式的所有 SKU,并在样式文档中添加一个名为 SKU 的新字段。 I am getting results like this after the $lookup.
在 $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
}
]
}
Which is expected as $lookup returns a matching array.这是预期的 $lookup 返回匹配的数组。 But I want my Styles document to look like this.
但我希望我的样式文档看起来像这样。
{
"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
}
}
}
Can someone give any idea how to structure the data like above in aggregation pipeline?有人可以知道如何在聚合管道中构造上述数据吗? Any help would be greatly appreciated.
任何帮助将不胜感激。 Thanks in advance.
提前致谢。
You could use $map
or $reduce
to convert the objects in the array to the form您可以使用
$map
或$reduce
将数组中的对象转换为表单
[
{
k: <key1>
v: <value1>
},
{
k: <key2>
v: <value2>
}
]
Then use $arrayToObject
which will convert the array to an object like:然后使用
$arrayToObject
将数组转换为一个对象,如:
{
<key1>: <value1>,
<key2>: <value2>
}
Together, this might look like:总之,这可能看起来像:
{$addFields: {
skus: {
$arrayToObject: {
$map: {
input: "$skus",
in: {
k: {$toString: "$$this.id"},
v: "$$this"
}
}
}
}
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.