【MongoDB】-Java实现对mongodb的And、Or、In操作

1)And(同时满足多个条件时用And)

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

2)Or(两个条件满足其中一个)

public void testOrSingleField(){    
    DBObject queryCondition = new BasicDBObject();          
    //age<15 OR age>27     
    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);       
}    

3)In(需要某个字段的值在某个范围时)

public void testIn(){    
    DBObject queryCondition = new BasicDBObject();          
    //age in [13, 47]    
    BasicDBList values = new BasicDBList();    
    values.add(13);    
    values.add(47);    
    queryCondition.put("age", new BasicDBObject("$in", values));    

    DBCursor dbCursor = coll.find(queryCondition);       
}    

你可能感兴趣的:(Java基础,MongoDB)