Mongodb,$ group

时间:2017-01-14 12:06:19

标签: mongodb mongodb-query aggregation-framework

我正在进行一些汇总,以获得有关产品中有多少产品的统计数据。

经过一些管道之后,我对此表示赞同:

[
  {
     topCategory: "Computer",
     mainCategory: "Stationary"
  },
  {
    topCategory: "Computer",
    mainCategory: "Laptop"
  },
  {
    topCategory: "Computer",
    mainCategory: "Stationary"
  },
  {
    topCategory: "Computer",
    mainCategory: "Stationary"
  },

通缉输出:

[
  {
    name: "Computer",
    count: 4,
    mainCategories: [
      {
         name: "Laptop",
         count: 2
      },
      {
         name: "Stationary",
         count: 2
      }
    ]
  }
]

到目前为止我的查询:

let query = mongoose.model('Product').aggregate([
    {
      $match:  {
        project:  mongoose.Types.ObjectId(req.params.projectId)
      }
    },
    { $project:  {
        _id: 0,
        topCategory: '$category.top',
        mainCategory: '$category.main',
      }
    },
 ]);

我知道我需要将$group$sum结合使用。我尝试了不同的方式,但无法让它发挥作用。

1 个答案:

答案 0 :(得分:2)

在这种情况下,首先您应该按mainCategory进行分组,然后按topCategory进行分组,如下所示

db.collection.aggregate({
  $group: {
    _id: "$mainCategory",
    "count": {
      $sum: 1
    },
    "data": {
      "$push": "$$ROOT"
    }
  }
}, {
  "$unwind": "$data"
}, {
  "$group": {
    "_id": "$data.topCategory",
    "count": {
      "$sum": 1
    },
    "mainCategories": {
      "$addToSet": {
    "name": "$_id",
    "count": "$count"
      }
    }
  }
}).pretty()