@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]) // 国ごとの店舗数を取得 for(obj in col.group(/* key */new BasicDBObject([country:true]), /* condition */new BasicDBObject(), /* initial */new BasicDBObject([scount:0, ssum:0]), /* reduce */"function(obj,prev){ prev.scount++; prev.ssum += obj.sales;}", /* finalize */"function(obj){ obj.savg = obj.ssum / obj.scount;}" )){ println obj["country"] + " - sales average:${obj.savg}" }
動作環境
Groovy 1.8.0, JDK6 Update22, gmongo 0.8, MongoDB 1.8.2
関連情報
gmongoのウェブサイト
https://github.com/poiati/gmongo
groovyとMongoDBのまとめ
0 件のコメント:
コメントを投稿