3

假设我需要知道我一生中赚了多少钱:我会在 SQL 中做什么是这样的:

select sum(salary) from employee_salary where employee_id=1000;

有没有一些简单的方法可以通过 mongoid、rails 在 mongoDB 中执行此操作?甚至不要想用 map/reduce 向我求婚。

我发现的最简单的方法是:

db.employee_salary.group(
    { 
        cond: { "employee_id":1000 },
        reduce: function(obj,prev) { prev.sum += obj.salary; },
        initial: { sum: 0 }
    }
)[0].sum;

但是看起来好难看...

4

1 回答 1

14

试试这个:

Employee.where(id: 1000).sum(:salary)
于 2012-05-09T13:36:13.963 回答