AND条件を指定する時の
コーディング方法です。条件は、30≦ score ≦ 70 です。
public final void findUseAnd(){
Mongo conn = null;
try {
conn = new Mongo("localhost", 27017);
} catch (Exception e) {
e.printStackTrace();
}
WriteConcern wc = new WriteConcern(1, 2000);
conn.setWriteConcern(wc);
DB db = conn.getDB("blog_app");
DBCollection coll = db.getCollection("users");
BasicDBObject mainQuery = new BasicDBObject();
BasicDBObject subQuery = new BasicDBObject("$gte", 30);
subQuery.append("$lte", 70);
mainQuery.put("score", subQuery);
System.out.println("query json = " + mainQuery.toString());
DBCursor cursor = coll.find(mainQuery);
System.out.println("count = " + cursor.count());
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject)cursor.next();
System.out.println(obj.toString());
}
}
結果は以下の通りです。
query json = { "score" : { "$gte" : 30 , "$lte" : 70}}
count = 2
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d1"} , "name" : "user-1" , "team" : 1.0 , "score" : 38.0}
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d5"} , "name" : "user-5" , "team" : 2.0 , "score" : 43.0}
最終更新:2013年05月09日 15:19