MongoDB thinks great value?

Here is my code below. I have to calculate how many times a repeating value is repeated. Here I have a specific meaning in the "results". I used collection.count () to calculate, but it does not work. please someone tell me where i should be wrong. 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); } }); 
+6
source share
2 answers

To get the occurrences of "col11" of individual values ​​of the field 'field1' in the collection 'col1' and write to a separate collection 'distinctCount'. Also allow disk space if the collection is huge.

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

While .distinct() works well for getting individual values ​​for a field, in order to actually get the number of occurrences, this is better for the aggregation structure :

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

The .distinct() method also performs an "abstract", from which the specified "excellent" field is actually located inside the array. In this case, you first need to call $unwind to process the elements of the array here:

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

So, the main work is mainly done in $group by grouping field values, which means the same as "excellent". $sum is a grouping operator, which in this case simply adds 1 for each occurrence of this value in the field for this collection.

+8
source

Source: https://habr.com/ru/post/975414/


All Articles