查询
对MongoDB进行新增、修改和删除后,最主要的功能就是对数据(集合)进行查询,MongoDB支持丰富的查询功能。
查询简介
使用find
命令可以查询集合中的文档,并返回符合要求的文档子集。查询命令的第一个参数是查询的模式,第二个参数是指定返回的键。查询的模式有些类似JPA中的查询模式,只需要表述需要的模式就行,例如:如果要查询属性name
为test
的文档,模式就是:{"name": "test"}
。返回的键可以通过声明指定的键即可,例如:如果要返回name
,声明就是:{"name": 1}
。
如果需要查询age
为20
的name
,查询命令参数就是:{"age": 20}, {"name": 1}
。
> db.foo.find({"age": 20}, {"name": 1})
{ "_id" : ObjectId("5d9ab1e940eabd2b62ced66f"), "name" : "test" }
> db.foo.find({"age": 20}, {"name": 1, "age": 1})
{ "_id" : ObjectId("5d9ab1e940eabd2b62ced66f"), "name" : "test", "age" : 20 }
> db.foo.find({"age": 20}, {"name": 1, "_id": 0})
{ "name" : "test" }
默认会返回属性
_id
,如果不需要可以声明{"_id": 0}
find
是和MongoDB交互的基础命令,可以通过它来查询集合中的文档(数据)。
对于java端的操作可以参考:
com.murdock.books.mongodbguide.chapter4.FindTest
使用MongoDB的Java客户端,进行查询文档的关键逻辑如下:
DBObject query = new BasicDBObject();
query.put("age", 20);
DBObject project = new BasicDBObject();
project.put("name", 1);
project.put("_id", 0);
DBCursor dbObjects = collection.find(query, project);
dbObjects.forEach(System.out::println);
dbObjects = collection.find(query);
dbObjects.forEach(System.out::println);
Collection.find()
方法的文档描述是:Select documents in collection and get a cursor to the selected documents.
,可以看到调用find
方法,返回的是指向符合查询条件要求的文档游标。只要我们获取了游标,我们就可以遍历它,访问符合我们要求的文档了。
这里和JDBC有些区别,传统的JDBC通过
Collection
和Statement
访问RDBMS后,得到的是数据集RowSet
根据条件查询
通过使用find
命令,可以查询集合中符合要求的文档,但是我们对于数据库的使用不是只限定在这种简单的操作,还有一些比较通用的查询要求,比如:范围查询等。
条件查询
在SQL查询中,可以使用>
或者<
来进行范围的控制,也就是比较操作符。在MongoDB中,由于查询的语句都是JSON,所以需要用转移字符来替换掉我们常用的比较操作符。
对应关系如下表:
类型 | 描述 |
---|---|
$lt |
less than,也就是 < |
$lte |
less than or equal,也就是 <= |
$gt |
greater than,也就是 > |
$gte |
greater than or equal,也就是 >= |
$ne |
not equal, 也就是 <> |
根据age
进行范围查询,先查询age
小于等于21
的。
> db.foo.find();
{ "_id" : ObjectId("5d9ab1e940eabd2b62ced66f"), "name" : "test", "age" : 20 }
{ "_id" : ObjectId("5dda6f29f75cb1b4beb2d95f"), "name" : "x", "age" : 21 }
> db.foo.find({"age": {"$lte" : 20}})
{ "_id" : ObjectId("5d9ab1e940eabd2b62ced66f"), "name" : "test", "age" : 20 }
> db.foo.find({"age": {"$gt" : 20}})
{ "_id" : ObjectId("5dda6f29f75cb1b4beb2d95f"), "name" : "x", "age" : 21 }
可以看到查询语句中,先给出了限定的文档字段age
,随后跟着对字段的限定内容。、
对于java端的操作可以参考:
com.murdock.books.mongodbguide.chapter4.ConditionFindTest
使用MongoDB的Java客户端,进行查询文档的关键逻辑如下:
DBObject query = new BasicDBObject();
DBObject condition = new BasicDBObject();
condition.put("$gt", 20);
query.put("age", condition);
DBCursor dbObjects = collection.find(query);
使用MongoDB的Java客户端,进行查询文档的关键逻辑如下:
$IN
在关系数据库中,可以使用in
查询来进行单key的多值查询,比如:
select * from user where age in (18, 19, 20);
上述SQL可以查询age
为18、19或者20的所有user
,而这种查询方式,MongoDB也有提供,方式和SQL很类似。
> db.foo.find()
{ "_id" : ObjectId("5d9ab1e940eabd2b62ced66f"), "name" : "test", "age" : 20 }
{ "_id" : ObjectId("5dda6f29f75cb1b4beb2d95f"), "name" : "x", "age" : 21 }
> db.foo.find({"age": {"$in": [20,21]}})