MongoDB计算不同的值?

Gun*_*tel 6 javascript mongodb node.js mongodb-query aggregation-framework

下面显示我的代码.我必须计算重复的不同值的次数.在这里,我在"结果"中存储了不同的值.我使用collection.count()来计算,但它不起作用.请任何人告诉我哪里有错误.非常感谢你 .

var DistinctIntoSingleDB = function(Collection,arr,opt,distVal,callback){
 Collection.find({}).distinct(distVal, function(err, results) {
      if(!err && results){
            console.log("Distinct Row Length :", results.length);
            var a,arr1 = [];
            for(var j=0; j<results.length; j++){
                collection.count({'V6': results[j]}, function(err, count) {
                      console.log(count)
                });

                arr1.push(results[j]+ " : " +a);
            }
            callback(results,arr1);
      }else{
           console.log(err, results);
           callback(results);
      }
 });
Run Code Online (Sandbox Code Playgroud)

Nei*_*unn 8

虽然.distinct()可以很好地获取字段的不同值,但为了实际获取出现次数,这更适合于聚合框架:

Collection.aggregate([
    { "$group": {
        "_id": "$field",
        "count": { "$sum": 1 }
    }}
],function(err,result) {

});
Run Code Online (Sandbox Code Playgroud)

.distinct()方法也从指定的"distinct"字段实际位于数组中"抽象".在这种情况下,您需要先调用$unwind以处理数组元素:

Collection.aggregate([
    { "$unwind": "$array" },
    { "$group": {
        "_id": "$array.field",
        "count": { "$sum": 1 }
    }}
],function(err,result) {

});
Run Code Online (Sandbox Code Playgroud)

因此,主要工作基本上是$group通过对字段值进行"分组"来完成的,这意味着与"不同"相同.这$sum是一个分组运算符,在这种情况下,只是1为该集合的字段中每次出现的值加起来.


blu*_*kin 0

获取集合“col1”上字段“field1”的不同值的出现次数,并将其写入单独的集合“distinctCount”。如果集合很大,还允许使用磁盘空间。

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