MongoDB和MySQL的一些常用的查询语句对比,MongoDB的一些语法及其查询示例。
查询所有
1 2 3 4
| select * from user;
db.user.find();
|
条件查询
1 2 3 4
| select * from user where name = '张三';
db.user.find({"name": "张三"});
|
多条件查询
1 2 3 4
| select * from user where name = '张三' and sex = 1;
db.user.find({"name": "张三"}, {"sex": 1});
|
范围查询
1 2 3 4 5 6 7 8 9 10
| select * from user where sex = 1 and age >10 and age <=50 and status != 0;
db.user.find({"sex": 1, "age": {"$gt": 10, "$lte": 50}, "status": {"$ne": 0}});
|
模糊查询
1 2 3 4
| select * from user where name like '%张%';
db.user.find({"name": /张/});
|
模糊查询,以 … 开头
1 2 3 4
| select * from user where name like '张%';
db.user.find({"name": /^张/});
|
查询记录条数
1 2 3 4
| select count(*) from user where name = '张三' and sex = 1;
db.user.find({"name": "张三"}, {"sex": 1}).count();
|
排序
1 2 3 4
| select * from user where name = '张三' and sex = 1 order by createTime desc;
db.user.find({"name": "张三"}, {"sex": 1}).sort({"createTime": -1});
|
时间查询
1 2 3 4 5
| select * from user where createTime > '2020-03-20' and createTime > '2020-03-24';
db.user.find({"createTime": {$gt: new Date(2020, 3, 20), $lt: new Date(2020, 3, 24)}}) db.user.find({"createTime": {$gt: ISODate("2020-03-20T00:00:00.000Z"), $lt: ISODate("2020-03-24T00:00:00.000Z")}})
|
进阶查询
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
| $in: in
$nin: not in
$mod: 取模运算,相当于 % 如:find({"count": {"$mod": [10, 1]}}) 查询 count % 10 = 1 的记录
$all: 全匹配,和in类似,但需要条件全部满足 如:字段 hobby: ["游泳", "篮球", "阅读"] find({"hobby": {"$all": ["游泳", "篮球", "阅读"]}}) 满足条件 find({"hobby": {"$all": ["游泳", "篮球"]}}) 不满足条件
$size: 匹配数组内元素数量 如:find({"hobby": {"$size": 3}}) 查询 hobby元素数量为 3的记录
$exists: 判断字段是否存在 如:find({"hobby": {"$exists": true}}) 查询 hobby字段存在的记录 如:find({"hobby": {"$exists": false}}) 查询 hobby字段不存在的记录
$type: 基于 bson type来匹配一个元素的类型 如:find({"age": {"$type": 1}}) 查询 age类型为 string的记录 如:find({"age": {"$type": 16}}) 查询 age类型为 int的记录
$not: 取反,相当于 !,可以用在逻辑判断前面 如:find({"age": {"$not": {"$gt": 36}}}) 查询 age<36的记录(这里相当于 $lt )
$or: 逻辑或,注意 $or中的所有表达式必须都有索引,否则会进行全表扫描 如:find({"$or": [{"age": 33}, {"age": 36}]}) 查询 age=33或 age=36的记录
|
后面继续补充。。。