1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| ⽅法find(): 查询 db.集合名称.find({条件⽂档}) ⽅法findOne():查询,只返回第⼀个 db.集合名称.findOne({条件⽂档}) ⽅法pretty(): 将结果格式化 db.集合名称.find({条件⽂档}).pretty()
等于: 默认是等于判断, 没有运算符 ⼩于:$lt (less than) ⼩于等于:$lte (less than equal) ⼤于:$gt (greater than) ⼤于等于:$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'})
使⽤"$in", "$nin" 判断是否在某个范围内 查询年龄为18、 28的学⽣ db.stu.find({age:{$in:[18,28]}})
使⽤//或$regex编写正则表达式 查询姓⻩的学⽣ db.stu.find({name:/^⻩/}) db.stu.find({name:{$regex:'^⻩'}})
⽅法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}})
|