java MongoDB查询(一)简单查询

时间:2023-11-11 23:57:50

前言

MongoDB的java驱动提供了查询的功能,查询条件也是bson对象,这篇就看下怎么进行简单的数据查询

1、数据结构

集合:firstCollection

数据内容:

{ "_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 }

2、连接数据库,拿到集合firstCollection

MongoClient mClient = new MongoClient("10.211.55.8");

DB db = mClient.getDB("test");

DBCollection collection = db.getCollection("firstCollection");

3、查询name为user1的对象

查询条件Json内容:

{"name": "user1"}

查询条件Java内容:

BasicDBObject queryObject = new BasicDBObject("name","user1");

执行过程:

DBObject obj = collection.findOne(queryObject);

这样就拿到了name为user1的对象了

4、查询name包含user的对象

这样模糊查询,也就类似于like查询是通过正则表达式来完成的

查询条件Json内容:

{“name”:/user/}

查询条件Java内容:

Pattern queryPattern = Pattern.compile("user", Pattern.CASE_INSENSITIVE);

BasicDBObject queryObject = new BasicDBObject("name",queryPattern);

执行过程:

Pattern queryPattern = Pattern.compile("user", Pattern.CASE_INSENSITIVE);

BasicDBObject queryObject = new BasicDBObject("name",queryPattern);

Cursor cursor = collection.find(queryObject);

while(cursor.hasNext()){

DBObject obj = cursor.next();

System.out.println(obj.toString());

}

5、查询年龄大于24的对象

查询条件Json内容:

{"age":{"$gt":24}}

查询条件Java内容:

两个Bson对象嵌套

BasicDBObject gt = new BasicDBObject("$gt",24);

BasicDBObject queryObject = new BasicDBObject("age",gt);

执行过程:

BasicDBObject gt = new BasicDBObject("$gt",24);

BasicDBObject queryObject = new BasicDBObject("age",gt);

Cursor cursor = collection.find(queryObject);

while(cursor.hasNext()){

DBObject obj = cursor.next();

System.out.println(obj.toString());

}

备注:

$gt:>

$gte:>=

$eq:        =

$ne:        !=

$lt:        <

$lte:        <=

$in:        in(后面的值为bson对象数组)

$nin:        not in(后面的值为bson对象数组)

这些操作符的用法和$gt类似,不在赘述

总结

通过这篇文章就可以对MongoDB进行简单的查询了,但是在具体业务中只有简单查询是不现实的,会有更多的与或关系,这戏内容将在下次文章中叙述。