Java 实现对mongodb and or 和and or联合查询操作

 转载:



AND:

public void testAnd(){    
    //agender='female' AND age > 27      
    DBObject queryCondition = new BasicDBObject();    
    queryCondition.put("agender", "female");    
    queryCondition.put("age", new BasicDBObject("$gt", 27));    
    DBCursor dbCursor = coll.find(queryCondition);    
    assertEquals(1, dbCursor.size());    
    assertEquals("Jane", dbCursor.next().get("username"));    
}    



OR:
public void testOrSingleField(){    
    DBObject queryCondition = new BasicDBObject();          
    //age<15 OR age>27    
    queryCondition = new BasicDBObject();    
    BasicDBList values = new BasicDBList();    
    values.add(new BasicDBObject("age", new BasicDBObject("$gt", 27)));    
    values.add(new BasicDBObject("age", new BasicDBObject("$lt", 15)));    
    queryCondition.put("$or", values);    
        
    DBCursor dbCursor = coll.find(queryCondition);    
    assertEquals(3, dbCursor.size());    
    assertEquals("tom", dbCursor.next().get("username"));    
}    


OR:

public void testOrMultiFields(){    
    DBObject queryCondition = new BasicDBObject();          
    //agender=female OR age<=23    
    queryCondition = new BasicDBObject();    
    BasicDBList values = new BasicDBList();    
    values.add(new BasicDBObject("agender", "female"));    
    values.add(new BasicDBObject("age", new BasicDBObject("$lte", 23)));    
    queryCondition.put("$or", values);    
        
    DBCursor dbCursor = coll.find(queryCondition);    
    assertEquals(4, dbCursor.size());    
    assertEquals("Jim", dbCursor.next().get("username"));    
}  


in:

public void testIn(){    
    DBObject queryCondition = new BasicDBObject();          
    //age in [13, 47]    
    queryCondition = new BasicDBObject();    
    BasicDBList values = new BasicDBList();    
    values.add(13);    
    values.add(47);    
    queryCondition.put("age", new BasicDBObject("$in", values));    
        
    DBCursor dbCursor = coll.find(queryCondition);    
    assertEquals(2, dbCursor.size());    
    assertEquals("tom", dbCursor.next().get("username"));    
}  




自己的:


and 和or的联合查询条件 (换成sql 这个查询条件就是  m=1 and (a=0 or a=1) and (b=1 or c=1))

public  DBObject getWhereField(){
		DBObject wheremap = new BasicDBObject();
		wheremap.put("m", 1);
//		
		
		DBObject[] orDbj = new BasicDBObject[2];
		orDbj[0] = new BasicDBObject("a", 0);
		orDbj[1] = new BasicDBObject("a", 1);
		
		DBObject[] orDbj1 = new BasicDBObject[2];
		orDbj1[0] = new BasicDBObject("b", 1);
		orDbj1[1] = new BasicDBObject("c", 1);
		
		BasicDBList values = new BasicDBList();    
		values.add(new BasicDBObject("$or", orDbj));
		values.add(new BasicDBObject("$or", orDbj1));
		
		wheremap.put("$and", values);
		return wheremap;
	}



你可能感兴趣的:(mongodb,java)