您当前的位置: 首页 >  mongodb

测试萌萌

暂无认证

  • 2浏览

    0关注

    1003博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

MongoDB常用28条查询语句

测试萌萌 发布时间:2020-11-20 21:26:22 ,浏览量:2

1、查询所有记录

db.userInfo.find();

相当于:

select* from userInfo;

默认每页显示20条记录,当显示不下的情况下,可以用it迭代命令查询下一页数据。注意:键入it命令不能带“;” 但是你可以设置每页显示数据的大小,用DBQuery.shellBatchSize= 50;这样每页就显示50条记录了。

2、查询去掉后的当前聚集集合中的某列的重复数据

db.userInfo.distinct("name");

会过滤掉 name 中的相同数据 相当于:

select distict name from userInfo;

3、查询 age = 22 的记录

db.userInfo.find({"age": 22});

相当于:

select * from userInfo where age = 22;

4、查询 age > 22 的记录

db.userInfo.find({age: {$gt: 22}});

相当于:

select * from userInfo where age > 22;

5、查询 age < 22 的记录

db.userInfo.find({age: {$lt: 22}});

相当于:

select * from userInfo where age = 25 的记录

db.userInfo.find({age: {$gte: 25}});

相当于:

select * from userInfo where age >= 25;

7、查询 age 25;

15、按照年龄排序 1 升序 -1 降序 升序:

db.userInfo.find().sort({age: 1});

相当于:

select * from userInfo order by age asc;

降序:

db.userInfo.find().sort({age: -1});

相当于:

select * from userInfo order by age desc;

17、查询前 5 条数据

db.userInfo.find().limit(5);

相当于:

select * from userInfo limit 5;

18、查询 10 条以后的数据

db.userInfo.find().skip(10);

19、查询在 6-10条 之间的数据

db.userInfo.find().limit(10).skip(5);

可用于分页,limit 是 pageSize,第n页时 skip 是 (n-1)*pageSize 相当于:

select * from userInfo limit 5,5;

20、and 查询 name = zhangsan, age = 22 的数据

db.userInfo.find({name: 'zhangsan', age: 22});

相当于:

select * from userInfo where name = 'zhangsan' and age = 22;

21、or 查询

db.userInfo.find({$or: [{age: 22}, {age: 25}]});

相当于:

select * from userInfo where age = 22 or age = 25;

注意多条件间用中括号[]包围。

22、in 查询

db.userInfo.find({age :{$in:[22,25]}});

相当于:

select * from userInfo where age in (22,25);

23、查询某个结果集的记录条数 统计数量

db.userInfo.find({age: {$gte: 25}}).count();

相当于:

select count(*) from userInfo where age >= 20;

skip(), limilt(), sort()三个放在一起执行的时候,执行的顺序是先 sort(), 然后是 skip(),最后是显示的 limit()。

24、查询某个时间段的数据(时间为日期类型,非字符串类型)

db.userInfo.find({createTime:{$gt:ISODate("2020-11-09T00:00:00Z")}});

相当于:

select * from userInfo where createTime> '2020-11-09 00:00:00'; 

25、对表中一字段进行统计求和

db.userInfo.aggregate({$group:{_id:null,score:{$sum:"$score"}}})

相当于:

SELECT SUM(score) from userInfo;

26、对表中一字段进行统计求平均值

db.userInfo.aggregate({$group:{_id:null,score:{$avg:"$score"}}})

相当于:

SELECT AVG(score) from userInfo;

27、对表中指定条件记录中的某字段求和

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"}}})

相当于:

SELECT SUM(score) from userInfo where createTime >= '2020-11-10 00:00:00' and createTime             
关注
打赏
1663571372
查看更多评论
0.1575s