【问题标题】:Count of distinct items mongodb不同项目的计数mongodb
【发布时间】:2016-03-21 15:17:19
【问题描述】:

鉴于 MongoDB 中的以下文档结构:

{ "_id" : ObjectId("56f00f745b4124b8b6b6f143"), "item" : "A" }
{ "_id" : ObjectId("56f00f8a5b4124b8b6b6f144"), "item" : "b" }
{ "_id" : ObjectId("56f00f935b4124b8b6b6f145"), "item" : "A" }

我正在尝试查找distinct 项目这些项目的数量。运行

db.test.distinct('item')

结果为@​​987654324@。如何输出每个 dinstinct 项目的count?示例输出为[ ["A",2] , ["b",1] ]

【问题讨论】:

    标签: mongodb distinct


    【解决方案1】:

    您可以使用aggregation framework 来执行此操作。按“项目”分组,然后计数:

    db.test.aggregate([{$group: {_id: "$item", count: {$sum: 1}}}])
    

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 2015-11-16
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多