mongodb 聚合管道中的嵌套组
Nested group in mongodb aggregation pipeline
我正在使用 Mongo 数据库,我有一个对象列表,我需要在类别 -> 子类别 -> 不同类型的子类别中分组。
您可以在这个 mongodb playground > https://mongoplayground.net/p/BfR7FT28XKN
中找到代码
我创建组类别->所有子类别。
但是如何将同名的子类别分组?
我的目标是实现这样的目标:
{
"_id": "Food and Drink",
"subCategories": [
{
"details": "Wine Bar",
"subCategory": "Bar",
},
{
"details": "Jazz and Blues Cafe",
"subCategory": "Nightlife",
},
{
"subCategory": "Restaurants",
"types": [
{
"details": "Mediterranean",
"subCategory": "Restaurants",
},
{
"details": "Mexican",
"subCategory": "Restaurants",
}
]
},
]
}
谢谢
这是您需要的。您需要先按类别和子类别进行分组。我已经按类型推送了完整的文档。您可以过滤字段或根据您的要求进行更改。
[{
"$match": {
"category": {
"$ne": null
},
"subCategory": {
"$ne": null
}
}
},
{
$group: {
_id: {
cat: "$category",
sub: "$subCategory",
},
docs: {
$push: "$$ROOT"
}
}
},
{
$group: {
_id: "$_id.cat",
subCategories: {
$push: {
subCategory: "$_id.sub",
types: "$docs"
}
}
}
}]
从最后阶段删除 types: "$docs"
,这就是您得到的
[{
"_id": "Community",
"subCategories": [
{
"subCategory": "Education"
},
{
"subCategory": "Disabled Persons Services"
}
]
},
{
"_id": "Food and Drink",
"subCategories": [
{
"subCategory": "Bar"
},
{
"subCategory": "Nightlife"
},
{
"subCategory": "Restaurants"
}
]
}]
我正在使用 Mongo 数据库,我有一个对象列表,我需要在类别 -> 子类别 -> 不同类型的子类别中分组。 您可以在这个 mongodb playground > https://mongoplayground.net/p/BfR7FT28XKN
中找到代码我创建组类别->所有子类别。 但是如何将同名的子类别分组?
我的目标是实现这样的目标:
{
"_id": "Food and Drink",
"subCategories": [
{
"details": "Wine Bar",
"subCategory": "Bar",
},
{
"details": "Jazz and Blues Cafe",
"subCategory": "Nightlife",
},
{
"subCategory": "Restaurants",
"types": [
{
"details": "Mediterranean",
"subCategory": "Restaurants",
},
{
"details": "Mexican",
"subCategory": "Restaurants",
}
]
},
]
}
谢谢
这是您需要的。您需要先按类别和子类别进行分组。我已经按类型推送了完整的文档。您可以过滤字段或根据您的要求进行更改。
[{
"$match": {
"category": {
"$ne": null
},
"subCategory": {
"$ne": null
}
}
},
{
$group: {
_id: {
cat: "$category",
sub: "$subCategory",
},
docs: {
$push: "$$ROOT"
}
}
},
{
$group: {
_id: "$_id.cat",
subCategories: {
$push: {
subCategory: "$_id.sub",
types: "$docs"
}
}
}
}]
从最后阶段删除 types: "$docs"
,这就是您得到的
[{
"_id": "Community",
"subCategories": [
{
"subCategory": "Education"
},
{
"subCategory": "Disabled Persons Services"
}
]
},
{
"_id": "Food and Drink",
"subCategories": [
{
"subCategory": "Bar"
},
{
"subCategory": "Nightlife"
},
{
"subCategory": "Restaurants"
}
]
}]