【问题标题】:Mongoose group and count猫鼬组和计数
【发布时间】:2017-06-07 01:23:04
【问题描述】:

下面是我的mongodb结构:

[{
    _id: '111',
    items: [{
        productId: '123'
    }]
}, {
    _id: '222',
    items: [{
        productId: '123'
    }, {
        productId: '456'
    }]
}, {
    _id: '333',
    items: [{
        productId: '123'
    }, {
        productId: '456'
    }, {
        productId: '789'
    }]
}]

我希望对productId 进行分组和计数,结果是:

[{
    productId: '123',
    count: 3
}, {
    productId: '456',
    count: 2
}, {
    productId: '789',
    count: 1
}]

好吧,我试过像这样使用aggregation,但我想我弄错了:

const aggregatorOpts = [{
  $group: {
    _id: "$items.productId",
    count: { $sum: 1 }
  }
}]

Model.aggregate(aggregatorOpts).exec()

我明白了:

result [
  { _id: [ '123' ], count: 1 },
  { _id: [ '123', '456' ], count: 1 },
  { _id: [ '123', '456', '789' ], count: 1 }
]

任何有关如何进行聚合的帮助可能都会受到赞赏,请不要假设模型有任何变化。

提前致谢!

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    试试这个。

        Model.aggregate([
            {
                $group: {
                   _id: '$items.productId',
                    points: {$count: '$items'}
               }
           }
         ]);
    

    这应该可行。

    【讨论】:

    • 未知组操作员$count。可能是语法错误。
    • 尝试将 "$count:'$items" 更改为 $sum:1"
    • 这将使我们回到初始点。 @Bertrand 的回答已经解决了。感谢您的帮助!
    【解决方案2】:

    分组前需要$unwinditems数组:

    const aggregatorOpts = [{
            $unwind: "$items"
        },
        {
            $group: {
                _id: "$items.productId",
                count: { $sum: 1 }
            }
        }
    ]
    
    Model.aggregate(aggregatorOpts).exec()
    

    给出:

    { "_id" : "789", "count" : 1 }
    { "_id" : "456", "count" : 2 }
    { "_id" : "123", "count" : 3 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2019-10-13
      相关资源
      最近更新 更多