@Grab(group='com.gmongo', module='gmongo', version='0.8') import com.mongodb.* import com.gmongo.* mongo = new GMongo("localhost", 27017) db = mongo.getDB("local") db["stores"].drop() // コレクションにオブジェクトを挿入する col = db["stores"] col.insert([country:"Japan", store:"store_A", sales:100]) col.insert([country:"Japan", store:"store_B", sales:120]) col.insert([country:"Japan", store:"store_C", sales:170]) col.insert([country:"United States", store:"store_D", sales:80]) col.insert([country:"United States", store:"store_E", sales:200]) col.insert([country:"United States", store:"store_F", sales:190]) col.insert([country:"United States", store:"store_G", sales:100]) // MapReduceで国ごとの売上平均を取得 println col.mapReduce( [ mapreduce:"stores", map:"""function(){ emit(this.country, {total_sales:this.sales, count:1}); }""", reduce:"""function(key, values){ var total = 0; var total_count = 0; for(var vi = 0;vi<values.length;vi++){ total += values[vi].total_sales; total_count += values[vi].count; } return {total_sales: total, count:total_count}; }""", out:"mr_result", query:new BasicDBObject(), finalize:"""function(key, value){ return {total_sales:value.total_sales, count:value.count, avg:value.total_sales/value.count} }""" ] ) // 結果を表示 db.mr_result.find().each { println it }
動作環境
Groovy 1.8.0, JDK6 Update22, gmongo 0.8, MongoDB 2.0
関連情報
gmongoのウェブサイト
https://github.com/poiati/gmongo
groovyとMongoDBのまとめ
0 件のコメント:
コメントを投稿