使用 $group 两次的 Mongodb 聚合 [英] Mongodb Aggregate using $group twice

查看:90
本文介绍了使用 $group 两次的 Mongodb 聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 mongo 中有一堆文档,结构如下:

I have a bunch of documents in mongo with the following structure:

{
    "_id" : "",
    "number" : 2,
    "colour" : {
        "_id" : "",
        "name" : "Green",
        "hex" : "00ff00"
    },
    "position" : {
        "_id" : "",
        "name" : "Defence",
        "type" : "position"
    },
    "ageGroup" : {
        "_id" : "",
        "name" : "Minor Peewee",
        "type" : "age"
    },
    "companyId" : ""
}

我目前正在使用 Mongo 的聚合按返回的 ageGroup.name 对文档进行分组:

I'm currently using Mongo's aggregate to group the documents by ageGroup.name which returns:

//Query
Jerseys.aggregate([
  {$match: { companyId: { $in: companyId } } },
  {$group: {_id: "$ageGroup.name", jerseys: { $push: "$$ROOT" }} }
]);

//returns
{
   _id: "Minor Peewee",
   jerseys: array[]
}

但我希望它也按年龄组内的 position.name 分组.即:

but I'd like it to also group by position.name within the age groups. ie:

{
  _id: "Minor Peewee",
  positions: array[]
}
//in positions array...
{
  _id: "Defence",
  jerseys: array[]
}
// or ageGroups->positions->jerseys if that makes more sense.

我尝试了多个组,但我认为我没有正确设置它们,我似乎总是得到一组 _id.我正在使用 Meteor 作为服务器,并且我正在使用 Meteor 方法进行操作.

I've tried multiple groups but I don't think I'm setting them up correctly I always seem to get an array of _id's. I'm using Meteor as the server and I'm doing it within a meteor method.

推荐答案

您可以在第一个分组阶段使用复合聚合 _id.

You can use a composite aggregate _id in the first grouping stage.

然后,您可以使用这些键中的一个作为最终聚合的主要"_id,并将另一个$push 放入另一个数组中.

Then, you can use one of those keys as the "main" _id of the final aggregate and $push the other into another array.

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" } } 
    } 
  } 
]);

这篇关于使用 $group 两次的 Mongodb 聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆