java对mongodb的and, in, or 经常使用操作

时间:2022-03-24 17:27:55

DBCollection dbcon = null;

DBObject query = new BasicDBObject();

BasicDBList values = new BasicDBList();

// or使用方法 --->> 查询薪水salary<3000 or salary>10000

values.add(new BasicDBObject("salary", new BasicDBObject("$gt",
10000)));

values.add(new BasicDBObject("salary", new BasicDBObject("$lt",
3000)));

query.put("$or", values);

DBCursor dbCursor = dbcon.find(query);

// end///

//查询 salary>1000 or age<22

values.add(new BasicDBObject("salary", new BasicDBObject("$gt",
10000)));

values.add(new BasicDBObject("age", new BasicDBObject("$lte",
22)));

query.put("$or", values);

DBCursor dbCursor2 = dbcon.find(query);

//end///

// in使用方法 --->>  查询 salary in [13, 47]

values.add(3000);

values.add(10000);

query.put("salary", new BasicDBObject("$in", values));

DBCursor dbCursor3 = dbcon.find(query);

//and使用方法 --->> salary>10000 and age<22

query.put("salary", new BasicDBObject("$gt", 10000));

query.put("age", new BasicDBObject("$lt", 22));

DBCursor dbCursor4 = dbcon.find(query);