目录
假设使用test数据库的user集合,有三条测试数据
查询
函数原型:db.collection_name.find(query,projection)
collection_name即集合的名称,query是查询条件(相当于SQL中的where子句),projection是投影条件(相当于SQL中的select子句),后两者都是可以不写的:
> use test
switched to db test
> db.user.insert({"name":"zhangsan","sex":"man","age":20,"hobby":"programming"})
WriteResult({ "nInserted" : 1 })
> db.user.find()
{ "_id" : ObjectId("5c3eef6d7da85af675c7c107"), "name" : "zhangsan", "sex" : "man", "age" : 20, "hobby" : "programming" }
{ "_id" : ObjectId("5c3eefee7da85af675c7c108"), "name" : "lisi", "sex" : "woman", "age" : 16, "hobby" : "music" }
{ "_id" : ObjectId("5c3ef0037da85af675c7c109"), "name" : "wangwu", "sex" : "man", "age" : 18, "hobby" : "read book" }
可以看到,什么都不写就相当于 select * from user
下面测试带条件的查询:
> db.user.find({name:"zhangsan"})
{ "_id" : ObjectId("5c3eef6d7da85af675c7c107"), "name" : "zhangsan", "sex" : "man", "age" : 20, "hobby" : "programming" }
> db.user.find({age:{$gt:17}})
{ "_id" : ObjectId("5c3eef6d7da85af675c7c107"), "name" : "zhangsan", "sex" : "man", "age" : 20, "hobby" : "programming" }
{ "_id" : ObjectId("5c3ef0037da85af675c7c109"), "name" : "wangwu", "sex" : "man", "age" : 18, "hobby" : "read book" }
> db.user.find({age:{$gt:17}},{name:1})
{ "_id" : ObjectId("5c3eef6d7da85af675c7c107"), "name" : "zhangsan" }
{ "_id" : ObjectId("5c3ef0037da85af675c7c109"), "name" : "wangwu" }
第一条语句相当于 select * from user where name="zhangsan",第二条相当于 select * from user where age>17
这里使用的文档结构比较简单,假如有嵌套文档,可以用"子文档名.子文档字段名"的形式来选择字段,多层嵌套依此类推
可以看到,查询条件中,key是不需要带上双引号的
$gt代表大于号,类似的运算符还有:
操作 | 格式 |
---|---|
等于 | {<key>:<value> } |
小于 | {<key>:{$lt:<value>}} |
小于或等于 | {<key>:{$lte:<value>}} |
大于 | {<key>:{$gt:<value>}} |
大于或等于 | {<key>:{$gte:<value>}} |
不等于 |
|
条件非 | {<key>:{$not:条件} |
逻辑或 | {$or:[{<key1>:<value1> },{<key2>:<value2> }]} |
非或 | {$nor:[{<key1>:<value1> },{<key2>:<value2> }]} |
条件与 | {$and:[条件1,条件2,…]} |
存在 | {<key>:{$exists:true/false}} |
类型查询 |
|
逻辑与就是多个查询条件并列,一个