嵌入式文档上的Mongoid聚合方法? [英] Mongoid aggregate methods on embedded docs?

查看:162
本文介绍了嵌入式文档上的Mongoid聚合方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I run aggregate, min, max, sum and friends on embedded docs?

例如:

获得一个地区所拥有的所有事件的平均成本,这些事件已被深深地嵌入其中.

Get the average cost of ALL events that a district has, where they are pretty deeply embedded.

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

显然不起作用.

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

也没有. 它给出了此错误消息:

Neither does that. It gives this error message:

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函数?

So is it possible or do I need to write my own map/reduce functions?

推荐答案

是的,MapReduce可以工作.您也可以使用游标来处理查询结果.喜欢:

Yes, MapReduce would work. You could also use cursors to process a query result. Like:

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;
});

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

You now have the min and max and can calculate the average and mean from the sum and count.

Mongodb无法直接使用其查询语言来计算聚合函数.实际上,该语句并不完全正确,因为有count()函数可对查询返回的结果数进行计数,还有group()函数.但是组功能非常类似于MapReduce,并且不能在分片数据库上使用.如果您对组功能感兴趣,请参见: http://www.mongodb. org/display/DOCS/Aggregation#Aggregation-Group

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

这篇关于嵌入式文档上的Mongoid聚合方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆