MongoDB+集成SpringBoot+索引+并发优化 - 基于《MongoDB进阶与实战:唐卓章》

本文介绍了MongoDB的安装、基本使用,包括MongoShell操作、索引基础、数据模型(BSON)、SpringBoot集成、审计实现等。深入探讨了并发处理,包括内置锁、MVCC机制,还涉及到了MongoDB的架构部署,如集群、分片和性能基准。文章最后提到了高级特性和架构管理的部分内容。
摘要由CSDN通过智能技术生成

MongoDB - 基于《MongoDB进阶与实战:唐卓章》

文章目录
MongoDB 官方网址 Community Download | MongoDB
MongoDB 教程 | 菜鸟教程 (runoob.com)
了解 MongoDB 看这一篇就够了【华为云分享】_华为云官方博客-CSDN博客
MongoDB CRUD操作 - MongoDB-CN-Manual (mongoing.com)

一、首次安装

服务安装

CentOS

## 安装依赖
yum -y install libcurl openssl

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UwwhBfWs-1664863195507)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/mongodb初始安装-1.png)]

## 从官网下载包,安装
wget -i -c https://repo.mongodb.org/yum/redhat/7/mongodb-org/5.0/x86_64/RPMS/mongodb-org-server-5.0.3-1.el7.x86_64.rpm
rpm -ivh mongodb-org-server-5.0.3-1.el7.x86_64.rpm
## 启动
systemctl restart mongod
systemctl status mongod

然后来看看它的默认端口27017

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-24WOzc78-1664863195508)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/mongodb初始安装-查看端口-1.png)]

配置文件修改

vim /etc/mongod.conf

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hq1dv2ox-1664863195508)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/mongodb-配置文件查看-1.png)]

可视化工具

MongoDB Compass Download | MongoDB

就无脑安装,没啥说明的,可惜的是好像没有CentOS版本,所以我装了Windows版

开始连接

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6Dfeu1WM-1664863195509)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/mongodb-可视化工具界面-1.png)]

Docker部署

Docker 安装 MongoDB | 菜鸟教程 (runoob.com)

二、基本使用

通过Linux命令行进入数据

root@9ac1e753f9ba:/# mongo
MongoDB shell version v5.0.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session {
    "id" : UUID("93ea0c3d-6584-4668-b716-b13f27a88622") }
MongoDB server version: 5.0.3
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
	https://community.mongodb.com
---
The server generated these startup warnings when booting: 
        2021-11-12T04:57:02.666+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2021-11-12T04:57:02.666+00:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
        2021-11-12T04:57:02.666+00:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> 

2.1 概念解析

宏观SQL与MongoDB

SQL术语/概念 MongoDB术语/概念 解释/说明
database database 数据库
table collection 数据库表/集合
row document 数据记录行/文档
column field 数据字段/域
index index 索引
table joins 表连接,MongoDB不支持
primary key primary key 主键,MongoDB自动将_id字段设置为主键

聚合(aggregate)

数据统计,类似于SQL中的count(*)

表达式 描述 实例
$sum 计算总和。 db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", num_tutorial : { s u m : " sum : " sum:"likes"}}}])
$avg 计算平均值 db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", num_tutorial : { a v g : " avg : " avg:"likes"}}}])
$min 获取集合中所有文档对应值得最小值。 db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", num_tutorial : { m i n : " min : " min:"likes"}}}])
$max 获取集合中所有文档对应值得最大值。 db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", num_tutorial : { m a x : " max : " max:"likes"}}}])
$push 将值加入一个数组中,不会判断是否有重复的值。 db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", url : { p u s h : " push: " push:"url"}}}])
$addToSet 将值加入一个数组中,会判断是否有重复的值,若相同的值在数组中已经存在了,则不加入。 db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", url : { a d d T o S e t : " addToSet : " addToSet:"url"}}}])
$first 根据资源文档的排序获取第一个文档数据。 db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", first_url : { f i r s t : " first : " first:"url"}}}])
$last 根据资源文档的排序获取最后一个文档数据 db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", last_url : { l a s t : " last : " last:"url"}}}])

2.2 MongoShell增删改查

创建集合
## 语法 name名称 options可选参数
db.createCollection(name, options)
字段 类型 描述
capped 布尔 (可选)如果为 true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。 当该值为 true 时,必须指定 size 参数。
autoIndexId 布尔 3.2 之后不再支持该参数。(可选)如为 true,自动在 _id 字段创建索引。默认为 false。
size 数值 (可选)为固定集合指定一个最大值,即字节数。 如果 capped 为 true,也需要指定该字段。
max 数值 (可选)指定固定集合中包含文档的最大数量。
删除集合
## delete collectionName
db.collection.drop()
## show All collection
show collections
插入/更新/删除/查询文档

插入

## insert(): 若插入的数据主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException 异常,提示主键重复,不保存当前数据
db.COLLECTION_NAME.insert(document)
## 如果 _id 主键存在则更新数据,如果不存在就插入数据
db.collection.insertOne()
db.collection.replaceOne()
## 插入多个文档
db.collection.insertMany()

更新

## query : update的查询条件,类似sql update查询内where后面的
## update : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
## upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入
## multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新
## writeConcern :可选,抛出异常的级别
db.collection.update(
   <query>,
   <update>,
   {
   
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

删除

## query :(可选)删除的文档的条件
## justOne : (可选)如果设为 true 或 1,则只删除一个文档,如果不设置该参数,或使用默认值 false,则删除所有匹配条件的文档
## writeConcern :(可选)抛出异常的级别
db.collection.remove(
   <query>,
   {
   
     justOne: <boolean>,
     writeConcern: <document>
   }
)

查询

## query :可选,使用查询操作符指定查询条件
## projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)
db.collection.find(query, projection)
## 易读格式
db.col.find().pretty()

条件依赖

操作 格式 范例 RDBMS中的类似语句
等于 {<key>:<value>} db.col.find({"by":"菜鸟教程"}).pretty() where by = '菜鸟教程'
小于 {<key>:{$lt:<value>}} db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值