数据查询
⽅法find(): 查询
db.集合名称.find({条件⽂档})
⽅法findOne():查询,只返回第⼀个
db.集合名称.findOne({条件⽂档})
⽅法pretty(): 将结果格式化
db.集合名称.find({条件⽂档}).pretty()
再查询中会用到一下内容:
⽐较运算符
等于: 默认是等于判断, 没有运算符
⼩于:
lte (less than equal)
⼤于:
gte
不等于:$ne
db.stu.find({age:{$gte:18}})
逻辑运算符
and:在json中写多个条件即可
查询年龄⼤于或等于18, 并且性别为true的学⽣
db.stu.find({age:{$gte:18},gender:true})
or:使⽤$or, 值为数组, 数组中每个元素为json
查询年龄⼤于18, 或性别为false的学⽣
db.stu.find({$or:[{age:{$gt:18}},{gender:false}]})
查询年龄⼤于18或性别为男⽣, 并且姓名是郭靖
db.stu.find({$or:[{age:{$gte:18}},{gender:true}],name:'gj'})
范围运算符
使⽤"
nin" 判断是否在某个范围内
查询年龄为18、 28的学⽣
db.stu.find({age:{$in:[18,28]}})
⽀持正则表达式
使⽤//或$regex编写正则表达式
查询姓⻩的学⽣
db.stu.find({name:/^⻩/})
db.stu.find({name:{$regex:'^⻩'}})
limit和skip
⽅法limit(): ⽤于读取指定数量的⽂档
先limit再skip比先skip再limit效率高
db.集合名称.find().limit(NUMBER)
查询2条学⽣信息
db.stu.find().limit(2)
⽅法skip(): ⽤于跳过指定数量的⽂档
db.集合名称.find().skip(NUMBER)
db.stu.find().skip(2)
同时使用
db.stu.find().limit(4).skip(5)
或
db.stu.find().skip(5).limit(4)
⾃定义查询*
使⽤$where后⾯写⼀个函数, 返回满⾜条件的数据
查询年龄⼤于30的学⽣
db.stu.find({
$where:function() {
return this.age>30;}
})
投影
在查询到的返回结果中, 只选择必要的字段
db.集合名称.find({},{字段名称:1,…})
参数为字段与值, 值为1表示显示, 值为0不显
特殊: 对于_id列默认是显示的, 如果不显示需要明确设置为0
db.stu.find({},{_id:0,name:1,gender:1})
排序
⽅法sort(), ⽤于对 集进⾏排序
db.集合名称.find().sort({字段:1,…})
参数1为升序排列
参数-1为降序排列
根据性别降序, 再根据年龄升序
db.stu.find().sort({gender:-1,age:1})
统计个数
⽅法count()⽤于统计结果集中⽂档条数
db.集合名称.find({条件}).count()
db.集合名称.count({条件})
db.stu.find({gender:true}).count()
db.stu.count({age:{$gt:20},gender:true})
消除重复
⽅法distinct()对数据进⾏去重
db.集合名称.distinct(‘去重字段’,{条件})
db.stu.distinct('hometown',{age:{$gt:18}})