假设每一条记录有一个叫做pv的整数字段,求整个集合中这个字段的和可以用如下方法: use testswitched to db test db.statistics.insertcreated_on: 2011-10-01, pv: 100 db.statistics.insertcreated_on: 2011-10-02, pv: 200 db.statistics.insertcreat
假设每一条记录有一个叫做pv的整数字段,求整个集合中这个字段的和可以用如下方法:
> use testswitched to db test> db.statistics.insert({created_on: 2011-10-01, pv: 100})> db.statistics.insert({created_on: 2011-10-02, pv: 200})> db.statistics.insert({created_on: 2011-10-03, pv: 300})> var reduce = function(key, values){... var count=0;... values.foreach(function(v) {... count+=v.pv;... });... return {count: count};... };> var s = db.statistics.find();> reduce(total_pv, s);
结果如下:
{ count : 600 }
link to this post!
原文地址:在mongodb中sum某个字段, 感谢原作者分享。