【问题标题】:Getting matching mongoose collections with group aggregate使用组聚合获取匹配的猫鼬集合
【发布时间】:2017-02-18 14:08:52
【问题描述】:

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

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集合的所有字段。像这样的:

[
 {
  "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"
 }
]

【问题讨论】:

    标签: mongoose


    【解决方案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}}
    ]);
    

    【讨论】:

    • 感谢您的代码。有用。有没有办法可以设置商店数组的限制。例如:如果我在 cat1 中有 20 个商店,是否可以将其设置为仅检索 5 个。我还可以对所有检索到的文档设置限制吗?
    • 不客气。看看这里stackoverflow.com/q/42258325/2683814 切片存储数组。您可以使用 $limit 阶段来限制检索到的文档。
    猜你喜欢
    • 2016-02-02
    • 2020-03-28
    • 2020-09-27
    • 2015-05-02
    • 2021-03-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多