我在mongo中有一堆文件,结构如下:
{
"_id" : "",
"number" : 2,
"colour" : {
"_id" : "",
"name" : "Green",
"hex" : "00ff00"
},
"position" : {
"_id" : "",
"name" : "Defence",
"type" : "position"
},
"ageGroup" : {
"_id" : "",
"name" : "Minor Peewee",
"type" : "age"
},
"companyId" : ""
}
Run Code Online (Sandbox Code Playgroud)
我目前正在使用Mongo的聚合来按ageGroup.name对文档进行分组,返回:
//Query
Jerseys.aggregate([
{$match: { companyId: { $in: companyId } } },
{$group: {_id: "$ageGroup.name", jerseys: { $push: "$$ROOT" }} }
]);
//returns
{
_id: "Minor Peewee",
jerseys: array[]
}
Run Code Online (Sandbox Code Playgroud)
但我希望它也按年龄组中的position.name分组.即:
{
_id: "Minor Peewee",
positions: array[]
}
//in positions array...
{
_id: "Defence",
jerseys: array[]
}
// or ageGroups->positions->jerseys if that makes more sense.
Run Code Online (Sandbox Code Playgroud)
我尝试了多个组,但我认为我没有正确设置它我似乎总是得到一个_id的数组.我正在使用Meteor作为服务器,而我正在使用流星方法.
您可以_id在第一个分组阶段使用复合聚合.
然后,您可以将其中一个键用作_id最终聚合的"主" ,将$push另一个键用作另一个数组.
Jerseys.aggregate([
{
$match: { companyId: { $in: companyId } }
},
{
$group: { // each position and age group have an array of jerseys
_id: { position: "$position", ageGroup: "$ageGroup" },
jerseys: { $push: "$$ROOT" }
}
},
{
$group: { // for each age group, create an array of positions
_id: { ageGroup: "$_id.ageGroup" },
positions: { $push: { position: "$_id.position", jerseys:"$jerseys" } }
}
}
]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1940 次 |
| 最近记录: |