嵌入式文档上的 Mongoid 聚合方法?

发布于 2025-01-08 03:40:11 字数 637 浏览 5 评论 0原文

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

例如:

获取一个地区所有活动的平均成本,这些活动在这些活动中根深蒂固。

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').

那么是否有可能或者我需要编写自己的映射/归约函数吗?

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

For example:

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)

Obviously doesn't work.

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').

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉生梦死 2025-01-15 03:40:11

是的,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 不具备直接用其查询语言计算聚合函数的能力。实际上,该说法并不完全正确,因为有 count() 函数来计算查询返回的结果数,并且有 group() 函数。但group函数很像MapReduce,不能在分片数据库上使用。如果您对分组功能感兴趣,请参见:http://www.mongodb。 org/display/DOCS/Aggregation#Aggregation-Group

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 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文