mongodb的简单map reduce

mongodb的orders collection里已经有了一些数据
> db.orders.find();
{ "_id" : ObjectId("5237b7807d76a3941f8774c8"), "user_id" : 305, "amount" : 300 }
{ "_id" : ObjectId("5237b7907d76a3941f8774c9"), "user_id" : 306, "amount" : 200 }
{ "_id" : ObjectId("5237b7987d76a3941f8774ca"), "user_id" : 307, "amount" : 205 }
{ "_id" : ObjectId("5237b7a37d76a3941f8774cb"), "user_id" : 305, "amount" : 200 }
{ "_id" : ObjectId("5237b7ae7d76a3941f8774cc"), "user_id" : 306, "amount" : 400 }
{ "_id" : ObjectId("5237b7b97d76a3941f8774cd"), "user_id" : 307, "amount" : 505 }
{ "_id" : ObjectId("5237b8cb7d76a3941f8774ce"), "user_id" : 308, "amount" : 5 }

现在用一个mapreduce任务来统计每个user_id的amount总量

要编写一个map函数和一个reduce函数
> function mapper(){emit(this.user_id,this.amount)}
> function reducer(keyUserId,amount){return Array.sum(amount)}

运行mapreduce job,其中用到了map函数和reduce函数

> db.orders.mapReduce(mapper,reducer,{out:"mrresult"})

结果会输出到mrresult 这个collection中

> db.mrresult.find()
{ "_id" : 305, "value" : 500 }
{ "_id" : 306, "value" : 600 }
{ "_id" : 307, "value" : 710 }
{ "_id" : 308, "value" : 5 }

猜你喜欢

转载自kabike.iteye.com/blog/1943217