假設每一條記錄有一個叫做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 test
switched 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!