MongoDB计算不同的值?
问题描述:
下面显示我的代码。我必须计算重复的不同值的次数。在这里,我在结果中存储了不同的值。我使用collection.count()来计算,但它不起作用。请任何人告诉我哪里有错误。非常感谢。
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);
}
});
答
获取字段'field1的不同值的出现'在集合'col1'上并写入单独的集合'distinctCount'。如果集合很大,也允许使用磁盘空间。
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}
)