我有以下数据:
{
"make" : "Toyota",
"name" : "Corolla",
"year" : "2012"
"color" : "Blue"
}
{
"make" : "Toyota",
"name" : "Camry",
"year" : "2016"
"color" : "Blue"
}
{
"make" : "Toyota",
"name" : "Prius",
"year" : "2012"
"color" : "Black"
}
{
"make" : "Nissan",
"name" : "PathFinder",
"year" : 2012.0
"color" : "Black"
}
{
"make" : "Nissan",
"name" : "Qashqai",
"year" : 2011.0
"color" : "Black"
}
{
"make" : "Nissan",
"name" : "X-Trail",
"year" : 2009.0
"color" : "Blue"
}
我想编写一个汇总查询,按make
分组,然后color
组内的make
分组。
所以我想要的结果的摘录看起来像这样
[{
_id: "Toyota"
colors: [
{
_id: "Black"
cars: [{
"make" : "Toyota",
"name" : "Prius",
"year" : "2012"
"color" : "Black"
}]
},
{
_id: "Blue"
cars:[{
"make" : "Toyota",
"name" : "Corolla",
"year" : "2012"
"color" : "Blue"
},
{
"make" : "Toyota",
"name" : "Camry",
"year" : "2016"
"color" : "Blue"
}]
}
]
},
{
.... Nissan cars
}]
我已经尝试了以下管道,并且有点接近我想要的结果,但它并不理想
db.Cars.aggregate(
// Pipeline
[
// Stage 1
{
$group: {
_id: {make: '$make', color: '$color'},
cars: {$push: '$$CURRENT'}
}
},
// Stage 2
{
$group: {
_id: '$_id.make',
colors: {$push: '$$CURRENT'}
}
},
]
);
结果如此(请注意颜色的_id
字段):
[{
"_id" : "Toyota",
"colors" : [
{
"_id" : {
"make" : "Toyota",
"color" : "Black"
},
"cars" : [
{
"make" : "Toyota",
"name" : "Prius",
"year" : "2012",
"color" : "Black"
}
]
},
{
"_id" : {
"make" : "Toyota",
"color" : "Blue"
},
"cars" : [
{
"make" : "Toyota",
"name" : "Corolla",
"year" : "2012",
"color" : "Blue"
},
{
"make" : "Toyota",
"name" : "Camry",
"year" : "2016",
"color" : "Blue"
}
]
}
]
}
...
]
编写查询以使输出更接近所需结果的任何帮助都很不错
答案 0 :(得分:1)
从$project
$addFields
或$map
阶段到colors._id
colors._id.color
管道
db.cars.aggregate(
[
{
$group: {
_id: {make: '$make', color: '$color'},
cars: {$push: '$$CURRENT'}
}
},
{
$group: {
_id: '$_id.make',
colors: {$push: '$$CURRENT'}
}
},
{$project : {colors : {$map : {input : "$colors", as : "color", in : { "_id" : "$$color._id.color", cars : "$$color.cars" }}}}}
]
).pretty()
输出
>db.cars.aggregate( [ {$project : {_id : 0}}, { $group: { _id: {make: '$make', color: '$color'}, cars: {$push: '$$CURRENT'} } }, { $group: { _id: '$_id.make', colors: {$push: '$$CURRENT'} } }, {$project : {colors : {$map : {input : "$colors", as : "color", in : { "_id" : "$$color._id.color", cars : "$$color.cars" }}}}} ] ).pretty()
{
"_id" : "Toyota",
"colors" : [
{
"_id" : "Black",
"cars" : [
{
"make" : "Toyota",
"name" : "Prius",
"year" : "2012",
"color" : "Black"
}
]
},
{
"_id" : "Blue",
"cars" : [
{
"make" : "Toyota",
"name" : "Corolla",
"year" : "2012",
"color" : "Blue"
},
{
"make" : "Toyota",
"name" : "Camry",
"year" : "2016",
"color" : "Blue"
}
]
}
]
}
....//output omitted