「MongoDB入門」com.mongodb.DBObjectの使い方
1.DBObjectのインポート
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
2.$match
DBObject match = (DBObject) JSON.parse(“{$match:{'status’:’1′,’time’:
{$gte:'"+beginDay+"',$lte:'"+endDay+"'}}}");
(beginDay-開始日付;endDay-終了日付)
3.$group
DBObject group = (DBObject) JSON.parse(“{$group:{_id:’$userId’,
count:{$sum:1},total:{$sum:’$amount’},maxSigle:{$max:’$amount’}}}");
検索操作
List<DBObject> list = new ArrayList<DBObject>();
list.add(match); list.add(group);
AggregationOutput Output = mongoTemplate.getCollection(“tblName").aggregate(list);
4.List<DBObject>のサンプル
DBObject match = (DBObject) JSON.parse(“{$match:{'status’:{$in:['0′,’1′]},
type:{$ne:11},’time’:{$gte:'"+beginDay+"',$lte:'"+endDay+"'}}}");
DBObject sort = (DBObject) JSON.parse(“{$sort:{'count’:-1}}");//ソート
List<DBObject> list = new ArrayList<DBObject>();
list.add(match);
list.add(group);
list.add(groupMatch);
list.add(project);
list.add(sort);
AggregationOutput catchOutPut = mongoTemplate.getCollection(“tblName")
.aggregate(list);//検索結果
5.BasicDBObject()の操作
BasicDBObject groupIndex = new BasicDBObject();
BasicDBObject distinctQuery = new BasicDBObject();
distinctQuery.put(“userId", new BasicDBObject(“$in", userIds));//UserIds配列
BasicDBObject initIndex = new BasicDBObject();
initIndex.put(“count", 0);//countの値をリセット
Javaコード
String reduce = “function(doc, prev) {if(doc.status==0){prev.count+= 1;};}";
List<Map<String, Object>> basicDBList = (List<Map<String, Object>>) mongoTemplate.
getCollection(“Collection").group(groupIndex, distinctQuery, initIndex, reduce, null);