Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

javascript - MongoDB count distinct value?

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 calculate but it's not work. please any one tell me where i have to mistake. Thank you very much .

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);
      }
 });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While .distinct() works well for just obtaining the distinct values for a field, in order to actually get the counts of occurrences, this is better suited to the aggregation framework:

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

});

Also the .distinct() method does "abstract" from where the specified "distinct" field is actually within an array. In this case you need to call $unwind first to process the array elements here:

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

});

So the main work is basically done in the $group by "grouping" on the field values, which means the same thing as "distinct". The $sum is a grouping operator which in this case just adds up 1 for each occurrence of that value in the field for that collection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...