1

如何在嵌入式文档上运行聚合、最小值、最大值、总和和朋友?

例如:

获取一个地区所有活动的平均成本,这些活动非常深入。

District.schools.all.events.all.costs.avg(:value)

显然行不通。

District.avg('schools.events.costs.value')

那也不行。它给出了这个错误信息:

Mongo::OperationFailure: Database command 'group' failed: (errmsg: 'exception: reduce
invoke failed: JS Error: TypeError: obj.schools 
has no properties reduce setup:1'; code:   '9010'; ok: '0.0').

那么有可能还是我需要编写自己的 map/reduce 函数?

4

1 回答 1

2

是的,MapReduce 可以工作。您还可以使用游标来处理查询结果。像:

min = 99999999;
max = -99999999;
sum = 0;
count = 0
db.School.find({}).forEach(function(s) {
    if (s.first.events.first.cost < min)
        min = s.first.events.first.cost;
    if (s.first.events.first.cost > max)
        max = s.first.events.first.cost;
    sum += s.first.events.first.cost;
    ++count;
});

您现在有了最小值和最大值,并且可以从总和和计数中计算平均值和平均值。

Mongodb does not have the ability to calculate the aggregate functions in its query language directly. Actually, that statement is not entirely true, since there is the count() function to count the number of results returned by a query, and there is the group() function. But the group function is a lot like a MapReduce, and cannot be used on sharded databases. If you are interested in the group function, see: http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group

于 2012-02-20T19:44:32.837 回答