MongoDB数据库常用28条查询语句总结

 更新时间:2023年05月16日 10:16:28   作者:起码有故事  
我们经常使用的MySQL是最流行的关系型数据库管理系统,随着时代的进步,互联网的发展关系型数据库已经不满足于互联网的需求,因此出现了非关系数据库,下面这篇文章主要给大家总结介绍了关于MongoDB数据库常用28条查询语句,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

初始MongoDB

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

  • database:数据库,SQL中的database含义。
  • collection:数据库表/集合,SQL中的table含义。
  • document:数据记录行/文档,SQL中的row含义。
  • field:数据字段/域,SQL中的column含义。
  • index:索引,SQL中的index含义。
  • primary key:主键,MongoDB自动将_id字段设置为主键,SQL中的primary key含义。

MongoDB特点

  • MongoDB 是一个面向文档存储的数据库,操作起来比较简单和容易。
  • 你可以在MongoDB记录中设置任何属性的索引 (如:FirstName="Sameer",Address="8 Gandhi Road")来实现更快的排序。
  • 你可以通过本地或者网络创建数据镜像,这使得MongoDB有更强的扩展性。
  • 如果负载的增加(需要更多的存储空间和更强的处理能力) ,它可以分布在计算机网络中的其他节点上这就是所谓的分片。
  • Mongo支持丰富的查询表达式。查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。
  • MongoDb 使用update()命令可以实现替换完成的文档(数据)或者一些指定的数据字段 。
  • Mongodb中的Map/reduce主要是用来对数据进行批量处理和聚合操作。
  • Map和Reduce。Map函数调用emit(key,value)遍历集合中所有的记录,将key与value传给Reduce函数进行处理。
  • Map函数和Reduce函数是使用Javascript编写的,并可以通过db.runCommand或mapreduce命令来执行MapReduce操作。
  • GridFS是MongoDB中的一个内置功能,可以用于存放大量小文件。
  • MongoDB允许在服务端执行脚本,可以用Javascript编写某个函数,直接在服务端执行,也可以把函数的定义存储在服务端,下次直接调用即可。
  • MongoDB支持各种编程语言:RUBY,PYTHON,JAVA,C++,PHP,C#等多种语言。
  • MongoDB安装简单。

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、查询在 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 < '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'
      }
    ]
  }
]

总结

到此这篇关于MongoDB数据库常用28条查询语句总结的文章就介绍到这了,更多相关MongoDB常用查询语句内容请搜索程序员之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持程序员之家!

相关文章

最新评论

?


http://www.vxiaotou.com