使用组聚合获得匹配的mongoose集合

时间:2017-02-18 05:45:00

标签: mongoose

我有一个看起来像这样的集合

var StoreSchema = new Schema({
name: String,
category: [String],
subCategory: [String],
});

示例数据如下所示:

[
 {
 'name':'Store1',
 'category':['Cat1','Cat2','Cat3'],
 'subCategory':['SubCat1','SubCat2']
 },
 {
 'name':'Store2',
 'category':['Cat2','Cat3','Cat4'],
 'subCategory':['SubCat1','SubCat2']
 },
 {
 'name':'Store3',
 'category':['Cat4','Cat3','Cat1'],
 'subCategory':['SubCat1','SubCat2']
 }
]

我希望按类别分组商店,我也要检索商店名称和ID。

我尝试使用此代码:

Store.aggregate([
        {$unwind: '$category'},
        {$group: { _id: '$category', count: {$sum: 1}}},
        {$project: {'_id':1, category: '$_id',count: '$count'}}
        ]);

我得到的输出是这样的:

[
 {
  "count": 2,
  "Category": "cat1"
 },
 {
  "count": 2,
  "category": "cat2"
 }
]

是否有可能获得商店收集的所有字段。像这样:

[
 {
  "stores": [{'name':'store1','id':'1'},{'name':'store3','id':'3'}],
  "count": 2,
  "Category": "cat1"
 },
 {
  "stores": [{'name':'store1','id':'1'},{'name':'store2','id':'2'}],
  "count": 2,
  "category": "cat2"
 }
]

1 个答案:

答案 0 :(得分:1)

您可以尝试以下聚合。使用$push运算符添加store

Store.aggregate([
    {$unwind: '$category'},
    {$group: { _id: '$category', count: {$sum: 1}, stores:{$push:{name:'$name', id:'$id'}}}},
    {$project: {_id:0, category: '$_id',count: 1, stores:1}}
]);