MongoDB常用28条查询语句(转)

转自MongoDB常用28条查询语句

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 < 22;

6、查询 age >= 25 的记录

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

相当于:

select * from userInfo where age >= 25;

7、查询 age <= 25 的记录

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

相当于:

select * from userInfo where age <= 25;

8、查询 age >= 23 并且 age <= 25 注意书写格式

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

相当于:

select * from userInfo where age>=23 and age <= 25;

9、查询 age != 25 的记录

db.userInfo.find({age: {$ne: 25}});
相当于:

select * from userInfo where age != 25;

10、查询 name 中包含 mongo 的数据 模糊查询用于搜索

db.userInfo.find({name: /mongo/});

相当于:

select * from userInfo where name like '%mongo%';

11、查询 name 中以 mongo 开头的

db.userInfo.find({name: /^mongo/});

相当于:

select * from userInfo where name like 'mongo%';

12、查询 name 中以 mongo 结尾的

db.userInfo.find({name: /mongo$/});

相当于:

select * from userInfo where name like ‘%mongo’;

模糊查询语法:{ : /pattern/ }
其中options值可以为:

i -- 不区分大小写。
m -- 匹配value中有换行符(\n)的情形,还有一个情形是:匹配规则中使用了锚,所谓的锚就是^ 开头, $ 结尾。
s -- 允许点字符(.)匹配所有的字符,包括换行符。
x -- 忽视所有空白字符。

13、查询指定列 name、age 数据

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

相当于:

select name, age from userInfo;

当然 name 也可以用 true 或 false,当用 ture 的情况下和 name:1 效果一样,如果用 false 就是排除 name,显示 name 以外的列信息。

14、查询指定列 name、age 数据, age > 25

db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});

相当于:

select name, age from userInfo where 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、查询在 [5, 15) 条 之间的数据

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

跳过前5条记录,只取接下来的10条数据。skip和limit, 当两者一起使用的时候, 不管其位置顺序,默认先skip,再limit。可用于分页,limit 是 pageSize,offset 是skip,相当于:

select * from userInfo limit 5,10;

关于 skip 和 limit 的优先级,可以参考:关于MongoDB的skip,limit,sort执行顺序问题

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 < '2020-11-11 00:00:00';

28、根据A表,匹配B表所有满足条件的集合,如根据用户表userInfo表中的userId字段找出userAdress表中所有地址的集合,其中userId也为userAdress中的字段。

假设 有 用户集合, 存储的测试数据 如下:

db.userInfo.insert([
{ "_id" : 1, "userId" : "xxxx", "username" : "ruink", "website" : "www.51ste.com" },
{ "_id" : 2, "userId" : "yyyy", "username" : "foosingy", "website" : "www.scgossip.com" }
])
假设 有 地址集合, 存储的测试数据 如下:

db.userAdress.insert([
{ "_id" : 1, "userId" : "xxxx", address: "测试地址1"},
{ "_id" : 2, "userId" : "yyyy", address: "测试地址2"},
{ "_id" : 3, "userId" : "xxxx", address: "测试地址3"},
])

查询语句:

db.userInfo.aggregate([
  {
    $lookup:
      {
        from: "userAdress",
        localField: "userId",
        foreignField: "userId",
        as: "address_detail"
      }
    },
  { $match : {"userId" :"xxxx"} }
])

上表为找出userId="xxxx"的所有地址的集合,查询结果如下:

复制

[
  {
    _id: 1,
    userId: 'xxxx',
    username: 'ruink',
    website:'www.51ste.com',
    address_docs: [
        {
          _id: 1,
          userId: 'xxxx',
          address: '测试地址1'
        },
        {
          _id: 3,
          userId: 'xxxx',
          address: '测试地址3'
        }
      ]
  }
]

注意:

字段是什么类型,那么查询时字段值的类型就应该是什么类型,比如如果字段类型是 NumberLog,那么查询时就应该执行查询类型为 NumberLog,如

db.userInfo.find({id: NumberLog(10)})

转自MongoDB常用28条查询语句

  • 16
    点赞
  • 171
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
在使用Mongodb进行查询时,可以使用不同的语句来满足不同的需求。例如,要查询一个集合中dimlist字段下存在url字段的数据,可以使用以下语句: db.getCollection('user').find({'dimlist.url': {$exists: true}}) 这个语句的意思是查询'user'集合中dimlist字段下存在url字段的数据。 另外,如果你想要进行更复杂的查询,例如在两个集合之间进行联合查询,你可以使用聚合操作来实现。以下是一个示例查询语句: db.userInfo.aggregate([ { $lookup: { from: "userAddress", localField: "userId", foreignField: "userId", as: "address_detail" } }, { $match: { "userId": "xxxx" } } ]) 这个语句的作用是将userInfo集合中的userId字段与userAddress集合中的userId字段进行关联查询,并将结果存储在address_detail字段中。然后,通过$match操作符来筛选出userId为"xxxx"的数据。 以上是关于Mongodb查询语句的简要介绍,希望对你有所帮助。如果有任何问题,请随时提问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Mongodb常用查询语句_笔记](https://blog.csdn.net/weixin_43785299/article/details/108130739)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [MongoDB常用查询语句](https://blog.csdn.net/weixin_53571731/article/details/131667022)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值