数据查询操作---------基本查询
1.查询所有的数据: db.xx.find()
2.指定条件查询 db.xx.find(查询条件)
3. 只查找符合条件的一个 db.xx.findOne()
4.pretty(): 将结果格式化 db.stu.findOne({gender:true}).pretty()
比较运算符的使用
小于:$lt 小于等于:$lte 大于:$gt 大于等于:$gte 不等于:$ne
例:查询年龄大于18的所有学生
db.stu.find({age:{$gte:18}})
逻辑运算符的使用
-
逻辑运算符主要指与、或逻辑
语法:db.xx.find({$and:[{条件1},{条件2}]})
$and: "查询年龄大于或等于18, 并且性别为true的学生"
用法一: db.stu.find({age:{$gte:18},gender:true})
用法二: db.stu.find({$and:[{age:{$gte:18},{gender:true}]})$or
db.stu.find({$or:[{age:18},{gender:false}]})
范围运算符的使用
-
$in: 显示在数组内;$nin:显示不在数组内的数据
查询年龄为18、 28的学⽣
db.stu.find({age:{$in:[18,28,38]}})
正则的使用
-
使⽤//或$regex编写正则表达式
查询sku以abc开头的数据
db.products.find({sku:/^abc/})查询sku以789结尾的数据
db.products.find({sku:{$regex:'789$'}})
自定义查询*
- 由于mongo的shell是一个js的执行环境 使⽤$where后⾯写⼀个函数, 返回满⾜条件的数据
查询年龄大于30的学生
db.stu.find({
$where:function() {
return this.age>30;}
})
skip、limit 和 project(投影)的使用
-
skip 跳过几个显示; limit 允许显示几个; 他们在该find()方法里,不分先后
跳过两个 显示4个 db.stu.find().skip(2).limit(4)
-
投影 显示哪些字段; 显示 true 不显示false
db.xx.find({查询条件},{字段:true})
db.stu.find({name:true})
sort、count、distinct 去重
sort 排序: -1降序 1 升序
年龄 排降序, 相同的按照id 降序 db.stu.find({}).sort({age:-1,_id:-1})count 统计个数
统计所有 db.xx.count()
根据条件 db.xx.find().count()db.xx.distinct("去重字段",{查询条件})
取出年龄小于 60岁的的同学名字 db.stu.distinct("name",{age:{$lt:60}})