4、查询
条件查询:
BasicDBObject condition = new BasicDBObject();
condition.put("name", "bruce");
condition.put("age", 26);
coll.find(condition);
condition.put("name", "bruce");
condition.put("age", 26);
coll.find(condition);
分页查询:
DBCursor cursor = coll.find().skip(0).limit(10);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
条件查询:
BasicDBObject condition = new BasicDBObject();
condition.put("age", new BasicDBObject("$gt", 50));
coll.find(condition);
比较符
"$gt": 大于
"$gte":大于等于
"$lt": 小于
"$lte":小于等于
"$in": 包含
//以下条件查询20<age<=30
condition.put("age", new BasicDBObject("$gt", 20).append("$lte", 30));
condition.put("age", new BasicDBObject("$gt", 50));
coll.find(condition);
比较符
"$gt": 大于
"$gte":大于等于
"$lt": 小于
"$lte":小于等于
"$in": 包含
//以下条件查询20<age<=30
condition.put("age", new BasicDBObject("$gt", 20).append("$lte", 30));
$exists
用来判断一个元素是否存在,如:
db.things.find( {a:{$exists:true}}); // 如果存在元素a,就返回true
$type
基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
db.things.find({a:{$type:2}}); // matches if a is a string
正则表达式
查询所有名字匹配 /joh?n/i 的记录。
Pattern pattern = Pattern.compile("joh?n", CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject("name", pattern);
DBCursor cursor = coll.find(query);
BasicDBObject query = new BasicDBObject("name", pattern);
DBCursor cursor = coll.find(query);