在MongoDB中分组和计数 [英] Group and count in MongoDB
问题描述
我试图对mongodb 2.0.1中每个组的元素数量进行分组和计数,但目前为止没有成功。
I'm trying to group and count the amount of elements for each group in mongodb 2.0.1, but with no success so far.
我的数据库模式看起来像例如:
My DB schema looks like :
{
"_id" : ObjectId("4ece7544853b4b0941000000"),
"ResultSet" : {
"Results" : [
{
"quality" : 87,
"state" : "Franche-Comté"
}
]
}
}
我一直在尝试各种方法,遵循不同的教程,但每次都是相同的结果:只有空组...我不明白为什么。
I've been trying all sort of methods, following different tutorials, but it is each time the same result : an only null group... which I don't understand why.
到目前为止我写的最好的查询是以下内容:
The best query I have written so far is the following :
db.extract_2000.group( {
cond: { "ResultSet.Results.quality": {$exists: true} },
key: {"ResultSet.Results.state": true},
reduce: function(obj, glob) { glob.total++; glob.quality += obj.ResultSet.Results.quality },
initial: { total: 0, quality: 0 },
finalize: function(glob) {glob.avgquality = glob.quality / glob.total}
})
返回(再一次):
[
{
"ResultSet.Results.state" : null,
"total" : 2000,
"quality" : NaN,
"avgquality" : NaN
}
]
我做错了什么?
What am I doing wrong ?
推荐答案
关键问题在于: key:{ResultSet.Results.state:true}
。 ResultSet.Results
是一个数组。当你要求 ResultSet.Results.state
时,你暗示某些类型的 for
循环在这里完成。 group
命令根本就不行。
This simply won't work as written. The key problem is here: key: {"ResultSet.Results.state": true}
. ResultSet.Results
is an array. When you ask for ResultSet.Results.state
you are implying some type of for
loop be done here. The group
command is simply not capable of this.
请尝试以下M / R:
Instead try the following M/R:
map = function() {
// Note that we emit once per result
foreach(var i in ResultSet.Results) {
key = this.ResultSet.Results[i];
value = { count: 1,
quality: this.ResultSet.Results[i].quality,
avg_quality: 0
};
emit(key, value);
}
}
reduce = function(key, values) {
// note that results has same fields as emitted value
var results = { count: 0, quality: 0, avg_quality: 0 };
foreach(var i in values){
results.count += values[i].count;
results.quality += values[i].quality;
// ignore avg_quality, we don't use it
}
return results;
}
您还必须编写 finalize
$ b
You will also have to write a finalize
for the average.
finalize = function(key, value) {
if (value.count > 0)
value.avg_quality = value.quality / value.count;
return value;
}
这篇关于在MongoDB中分组和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!