OR条件を指定する時の
コーディング方法です。条件は、score < 30 OR 70 < score です。
public final void findUseOr() {
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 query1 = new BasicDBObject("$lt", 30);
BasicDBObject query11 = new BasicDBObject("score", query1);
BasicDBObject query2 = new BasicDBObject("$gt", 70);
BasicDBObject query21 = new BasicDBObject("score", query2);
ArrayList<BasicDBObject> myList = new ArrayList<BasicDBObject>();
myList.add(query11);
myList.add(query21);
BasicDBObject query3 = new BasicDBObject("$or", myList);
System.out.println("query json = " + query3.toString());
DBCursor cursor = coll.find(query3);
System.out.println("count = " + cursor.count());
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject)cursor.next();
System.out.println(obj.toString());
}
}
結果は以下
query json = { "$or" : [ { "score" : { "$lt" : 30}} , { "score" : { "$gt" : 70}}]}
count = 8
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d0"} , "name" : "user-0" , "team" : 0.0 , "score" : 24.0}
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d2"} , "name" : "user-2" , "team" : 2.0 , "score" : 26.0}
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d3"} , "name" : "user-3" , "team" : 0.0 , "score" : 82.0}
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d4"} , "name" : "user-4" , "team" : 1.0 , "score" : 79.0}
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d6"} , "name" : "user-6" , "team" : 0.0 , "score" : 79.0}
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d7"} , "name" : "user-7" , "team" : 1.0 , "score" : 93.0}
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d8"} , "name" : "user-8" , "team" : 2.0 , "score" : 14.0}
{ "_id" : { "$oid" : "5184c79dc401ef5c9cf0f8d9"} , "name" : "user-9" , "team" : 0.0 , "score" : 22.0}
最終更新:2013年05月16日 14:46