mongodb 與 或 多條件查詢java
數據:mongodb
{ "_id" : ObjectId("55adba52fa1f3cf038c2aea6"), "name" : "user0", "age" : 22, "sex" : 0 } { "_id" : ObjectId("55adba52fa1f3cf038c2aea7"), "name" : "user1", "age" : 23, "sex" : 1 } { "_id" : ObjectId("55adba52fa1f3cf038c2aea8"), "name" : "user2", "age" : 24, "sex" : 0 } { "_id" : ObjectId("55adba52fa1f3cf038c2aea9"), "name" : "user3", "age" : 25, "sex" : 1 } { "_id" : ObjectId("55adba52fa1f3cf038c2aeaa"), "name" : "user4", "age" : 26, "sex" : 0 } { "_id" : ObjectId("55adba52fa1f3cf038c2aeab"), "name" : "user5", "age" : 27, "sex" : 1 }
代碼:json
@Test public void testMongo(){ MongoClient mClient = new MongoClient("127.0.0.1"); DB db = mClient.getDB("zydb"); DBCollection collection = db.getCollection("firstCollection"); //{"$and":[{"age":{"$gt":23}},{"sex":1}]} BasicDBObject ageObj = new BasicDBObject("age",new BasicDBObject("$gt",23)); BasicDBObject sexObj = new BasicDBObject("sex",1); BasicDBObject andObj = new BasicDBObject("$and", Arrays.asList(ageObj,sexObj)); Cursor cursor = collection.find(andObj); while(cursor.hasNext()){ DBObject obj = cursor.next(); System.out.println(obj.toString()); } //{"$or":[{"name":"user2"},{"name":"user3"}]} BasicDBObject user2Obj = new BasicDBObject("name","user2"); BasicDBObject user3Obj = new BasicDBObject("name","user3"); BasicDBObject orObj = new BasicDBObject("$or",Arrays.asList(user2Obj,user3Obj)); Cursor cursor2 = collection.find(orObj); while(cursor2.hasNext()){ DBObject obj = cursor2.next(); System.out.println(obj.toString()); } }
結果:3d
{ "_id" : { "$oid" : "57e9e3d8e08ed42d9c8ba5e2"} , "name" : "user3" , "age" : 25.0 , "sex" : 1.0} { "_id" : { "$oid" : "57e9e40de08ed42d9c8ba5e4"} , "name" : "user5" , "age" : 27.0 , "sex" : 1.0} { "_id" : { "$oid" : "57e9e3c8e08ed42d9c8ba5e1"} , "name" : "user2" , "age" : 24.0 , "sex" : 0.0} { "_id" : { "$oid" : "57e9e3d8e08ed42d9c8ba5e2"} , "name" : "user3" , "age" : 25.0 , "sex" : 1.0}