MongoDB 是一种流行的 NoSQL 数据库,以其灵活的文档结构和强大的查询功能而闻名。 掌握这些查询技巧,可以显著提高数据检索的效率。
基础查询
-
查询所有记录
db.userInfo.find();相当于 SQL 中的
select * from userInfo;。 MongoDB 默认每页显示 20 条记录,可以使用it 命令迭代查看下一页。可以通过DBQuery.shellBatchSize = 50;设置每页显示的数据量。 -
查询去重后的某列数据
db.userInfo.distinct("name");相当于 SQL 中的
select distinct name from userInfo;,可以过滤掉name字段中的重复数据。 -
条件查询
- 查询
age = 22的记录:
db.userInfo.find({"age": 22});相当于 SQL 中的
select * from userInfo where age = 22;。- 查询
age > 22的记录:
db.userInfo.find({age: {$gt: 22}});相当于 SQL 中的
select * from userInfo where age > 22;。类似的,可以使用
$lt(小于),$gte(大于等于),$lte(小于等于),$ne(不等于)进行条件查询。- 查询
age >= 23 并且 age <= 25的记录:
db.userInfo.find({age: {$gte: 23, $lte: 25}});相当于 SQL 中的
select * from userInfo where age>=23 and age <= 25;。 - 查询
模糊查询
MongoDB 使用正则表达式进行模糊查询。
- 查询
name 中包含mongo的数据:
db.userInfo.find({name: /mongo/});
相当于 SQL 中的 select * from userInfo where name like '%mongo%';。
- 查询
name 中以mongo开头的:
db.userInfo.find({name: /^mongo/});
相当于 SQL 中的 select * from userInfo where name like 'mongo%';。
- 查询
name 中以mongo结尾的:
db.userInfo.find({name: /mongo$/});
相当于 SQL 中的 select * from userInfo where name like '%mongo';。
正则表达式选项:
-
i:不区分大小写。 -
m:匹配包含换行符的 value。 -
s:允许点字符.匹配所有字符,包括换行符。 -
x:忽略所有空白字符。
投影查询
指定返回的字段。
db.userInfo.find({}, {name: 1, age: 1});
相当于 SQL 中的 select name, age from userInfo;。 name: 1 表示返回 name 字段,age: 1 表示返回 age 字段。 也可以使用 name: true 达到同样的效果。 如果使用 name: false,则表示排除 name 字段,返回其他字段。
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相当于 SQL 中的 select name, age from userInfo where age > 25;。
排序、限制和跳过
-
排序
db.userInfo.find().sort({age: 1}); // 升序 db.userInfo.find().sort({age: -1}); // 降序相当于 SQL 中的
select * from userInfo order by age asc; 和select * from userInfo order by age desc;。 -
限制
db.userInfo.find().limit(5);相当于 SQL 中的
select * from userInfo limit 5;。 -
跳过
db.userInfo.find().skip(10);跳过前 10 条数据。
-
分页
db.userInfo.find().limit(10).skip(5);相当于 SQL 中的
select * from userInfo limit 5,5;。 可以用于分页查询,limit 表示每页显示的数量(pageSize),skip 表示跳过的数量,第 n 页时skip 的值为(n-1)*pageSize。
组合查询
-
AND 查询
db.userInfo.find({name: 'zhangsan', age: 22});相当于 SQL 中的
select * from userInfo where name = 'zhangsan' and age = 22;。 -
OR 查询
db.userInfo.find({$or: [{age: 22}, {age: 25}]});相当于 SQL 中的
select * from userInfo where age = 22 or age = 25;。 -
IN 查询
db.userInfo.find({age :{$in:[22,25]}});相当于 SQL 中的
select * from userInfo where age in (22,25);。
统计
-
统计数量
db.userInfo.find({age: {$gte: 25}}).count();相当于 SQL 中的
select count(*) from userInfo where age >= 20;。 -
求和
db.userInfo.aggregate({$group:{_id:null,score:{$sum:"$score"}}})相当于 SQL 中的
SELECT SUM(score) from userInfo; -
求平均值
db.userInfo.aggregate({$group:{_id:null,score:{$avg:"$score"}}})相当于 SQL 中的
SELECT AVG(score) from userInfo; -
条件求和
db.userInfo.aggregate({$match:{createTime:{$gte:ISODate("2020-11-10T00:00:00Z"),$lt:ISODate("2020-11-11T00:00:00Z")}}},{$group:{_id:null,score:{$sum:"$score"}}})相当于 SQL 中的
SELECT SUM(score) from userInfo where createTime >= '2020-11-10 00:00:00' and createTime < '2020-11-11 00:00:00';
$lookup 多表关联查询
$lookup 操作符可以实现多表关联查询。 类似于 SQL 中的 JOIN 操作。
db.userInfo.aggregate([
{
$lookup:
{
from: "userAdress",
localField: "userId",
foreignField: "userId",
as: "address_detail"
}
},
{ $match : {"userId" :"xxxx"} }
])
以上代码演示了根据 userInfo 表中的 userId 字段,查找 userAdress 表中所有匹配的地址集合。
-
from: 要连接的集合名称。 -
localField:userInfo集合中用于连接的字段。 -
foreignField:userAdress集合中用于连接的字段。 -
as: 连接后,将匹配的userAdress 文档放入userInfo 文档的address_detail字段中。
注意事项
字段类型要匹配,如果字段类型是 NumberLog,那么查询时也应该使用 NumberLog 类型。
db.userInfo.find({id: NumberLog(10)})
总结
掌握这些 MongoDB 查询语句,可以更加高效地进行数据检索和分析。 希望这篇博客对您有所帮助!