MongoDB文档查询操作
MongoDB 查询文档使用 find() 方法。
find() 方法以非结构化的方式来显示所有文档。
find()
没有传任何参数find({})
都表示没有查询条件,查询所有的数据。
我们使用的数据库名为“test”,集合名为“testlist”,以下是我们插入的数据:
db.testlist.insert({name:"Linda",age:33,description:"认真刻苦努力",likes:100});
db.testlist.insert({name:"Anna",age:24,description:"负责,技术好,上进",likes:200});
db.testlist.insert({name:"Annie",age:26,description:"认真努力,技术好",likes:200});
db.testlist.insert({name:"Peter",age:30,description:"平易近人,管理好",likes:300});
db.testlist.insert({name:"Alice",age:28,description:"还好还好还好",likes:300});
使用find()
来查看我们添加的数据:
如果有查询条件,传入查询条件即可,如下查询age为26的文档:
db.testlist.find({age:26});
pretty()方法是以格式化方式显示数据。
如果查询条件字段不止一个,多个字段之间的关系是AND,如下表示查询name为“Linda”并且age为33的文档:
db.testlist.find({name:"Linda",age:33});
默认情况下,每次查询都会返回所有的key/value对,那我们其实也可以自定义返回的字段,比如,只返回age字段,其他字段都不返回
db.testlist.find({},{age:1})
参数1表示返回某一个字段,0表示不返回某一个字段
当我们设置只返回age字段的时候,_id默认还是返回的,如果我们也不想返回_id,我们就可以设置_id为0
db.testlist.find({},{age:1,_id:0})
MongoDB条件操作符
条件操作符用于比较两个表达式并从mongoDB集合中获取数据。
MongoDB中条件操作符有:
- (>) 大于 - $gt
- (<) 小于 - $lt
- (>=) 大于等于 - $gte
- (<= ) 小于等于 - $lte
MongoDB (>) 大于操作符 - $gt
如你想获取 “testlist” 集合中 “age” 大于 26 的数据,你可以使用以下命令:
db.testlist.find({age:{$gt:26}});
类似于SQL语句:
Select * from testlist where age > 26;
输出结果:
MongoDB (>=) 大于等于操作符 - $gte
如你想获取 “testlist” 集合中 “age” 大于等于 26 的数据,你可以使用以下命令:
db.testlist.find({age:{$gte:26}});
类似于SQL语句:
Select * from testlist where age >=26
输出结果为:
MongoDB (<) 小于操作符 - $lt
如你想获取 “testlist” 集合中 “age” 小于 26 的数据,你可以使用以下命令:
db.testlist.find({age:{$lt:28}});
类似于SQL语句:
Select * from testlist where age < 28
输出结果为:
MongoDB (<=) 小于等于操作符 - $lte
如你想获取 “testlist” 集合中 “age” 小于 28 的数据,你可以使用以下命令:
db.testlist.find({age:{$lte:28}});
类似于SQL语句:
Select * from testlist where age <= 28
输出结果为:
MongoDB 使用 (<) 和 (>) 查询 - $lt 和 $gt
如你想获取 “testlist” 集合中 “age” 小于 30 大于24 的数据,你可以使用以下命令:
db.testlist.find({age:{$lt:30,$gt:24}});
类似于SQL语句:
Select * from testlist where age >24 AND age<30
**输出结果为:
模糊查询
-
查询字段
name
以"A"开头的文档(数据)db.testlist.find({name:/^A/});
输出结果如下
-
查询字段
name
中包含“e的文档”db.testlist.find({name:/e/});
输出结果如下:
-
查询字段
name
以“e”结尾的文档db.testlist.find({name:/e$/});
输出结果如下:
$in
$in有点类似于SQL中的in关键字,表示查询某一个字段在某一个范围中的所有文档
db.testlist.find({age:{$in:[24,33]}})
表示查询age为24或33的所有文档
$nin表示查询不在某一个字段在某一个范围中的所有文档
db.testlist.find({age:{$nin:[24,33]}})
表示查询age不为24或33的所有文档
$or
$or有点类似于SQL中的or关键字,表示多个查询条件之间是或的关系
db.testlist.find({$or:[{name:"Linda"},{age:24}]})
表示查询name为“Linda”或age为24的文档;
$type
$type可以用来根据数据类型查找数据,比如我想要查找x类型为数字的文档,如下:
db.sang_collect.find({x:{$type:1}})
1表示数字,其他数据类型对应的数字参见下表。
类型 | 对应数字 |
---|---|
Double | 1 |
String | 2 |
Object | 3 |
Array | 4 |
Binary data | 5 |
Boolean | 8 |
Date | 9 |
Null | 10 |
Regular Expression | 11 |
如:想获取‘demolist’集合中‘dis’为String的数据,使用以下命令:
db.demolist.find({dis:{$type:2}})
或db.demolist.find({dis:{$type:"string"}})
注意:type的值为数字或是string\color{red}{注意:type的值为数字或是string}注意:type的值为数字或是string
$not
$not用来执行取反操作,比如我想要查询所有dis的类型不为数字的文档,如下:
db.demolist.find({dis:{$not:{$type:1}}})