MongoDB count distinct value?

前端 未结 2 1414
夕颜
夕颜 2020-12-11 04:57

Here below show my code. I have to calculate the how many times distinct value repeated. Here i have store distinct value in \"results\".I used collection.count() to calcula

2条回答
  •  天涯浪人
    2020-12-11 05:48

    To get occurrences of distinct values of a field 'field1' on a collection 'col1' and write to a separate collection 'distinctCount'. Also allow to use disk space in case the collection is huge.

    db.col1.aggregate(
              [{$group: {
                  _id: "$field1",
                  count: { $sum : 1 }
                }}, {
                $group: {
                  _id: "$_id",
                  count: { $sum : "$count" }
                }},{
                  $out: "distinctCount"
                }],
             {allowDiskUse:true}
    )
    

提交回复
热议问题