一.什么是MongoDB
MongoDB 是一个文档型数据库,数据以类似 JSON 的文档形式存储。
MongoDB 的设计理念是为了应对大数据量、高性能和灵活性需求。
MongoDB 使用集合(Collections)来组织文档(Documents),每个文档都是由键值对组成的。
数据库(Database):存储数据的容器,类似于关系型数据库中的数据库。
集合(Collection):数据库中的一个集合,类似于关系型数据库中的表。
文档(Document):集合中的一个数据记录,类似于关系型数据库中的行(row),以 BSON 格式存储。
MongoDB 将数据存储为一个文档,数据结构由键值 (key=>value) 对组成,文档类似于 JSON 对象,字段值可以包含其他文档,数组及文档数组。
1.主要特点
文档导向的存储:MongoDB 是一个面向文档的数据库,它以 JSON-like 的格式存储数据,使得数据结构更加灵活和丰富。
索引优化查询:MongoDB 允许用户为文档中的任意属性创建索引,例如 FirstName 和 Address,从而提高查询效率和排序性能。
数据镜像与扩展性:通过本地或网络创建数据的副本,MongoDB 实现了强大的数据冗余和扩展能力。
水平扩展与分片:面对增加的负载,MongoDB 可以通过分片技术将数据分布到计算机网络中的其他节点上,实现水平扩展。
强大的查询语言:MongoDB 使用 JSON 格式的查询语法,支持复杂的查询表达式,包括对内嵌对象和数组的查询。
数据更新:利用 update () 命令,MongoDB 能够替换整个文档或更新指定的数据字段。
2.MongoDB概念解析
SQL 术语 / 概念 | MongoDB 术语 / 概念 | 解释 / 说明 |
---|---|---|
database | database | 数据库 |
table | collection | 数据库表 / 集合 |
row | document | 数据记录行 / 文档 |
column | field | 数据字段 / 域 |
index | index | 索引 |
table joins | 表连接,MongoDB 不支持 | |
primary key | primary key | 主键,MongoDB 自动将_id 字段设置为主键 |
二.MongoDB安装
安装前需要安装各个Linux平台依赖包
dnf -y install openssl libcurl
解压安装包
tar zxvf mongodb-linux-x86_64-rhel8-8.0.8.tgz
将解压包拷贝到指定目录
mv mongodb-linux-x86_64-rhel8-8.0.8.tgz /usr/local/mongodb
MongoDB的可执行文件在bin目录下
cd /usr/local/mongodb
cd bin/
vim /etc/profile
在末尾添加一行 : export /usr/local/mongodb/bin:$PATH
source /etc/profile
创建数据库目录
[root@localhost ~]#mkdir -p /var/lib/mongo
[root@localhost ~]#mkdir -p /var/log/mongodb
由于mongodb依赖openssl11,需要编译安装openssl11
[root@localhost ~]# dnf install -y gcc make perl
[root@localhost ~]# tar xzf openssl-1.1.1w.tar.gz
[root@localhost ~]# cd openssl-1.1.1w
[root@sentinel01 openssl-1.1.1w]#./config --prefix=/opt/openssl11 --openssldir=/opt/openssl11/ssl
[root@sentinel01 openssl-1.1.1w]#make -j2
[root@sentinel01 openssl-1.1.1w]#make install
设置openssl11的环境变量
[root@localhost ~]# echo 'export LD_LIBRARY_PATH=/opt/openssl11/lib:$LD_LIBRARY_PATH' | sudo tee /etc/profile.d/openssl11.sh
[root@localhost ~]# source /etc/profile.d/openssl11.sh
接下来启动Mongodb服务
[root@localhost ~]# mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork
看到以下信息,说明启动成功
[root@localhost ~]# mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork
about to fork child process, waiting until server is ready for connections.
forked process: 12102
child process started successfully, parent exiting
三.MongoDB Shell
MongoDB Shell 是 MongoDB 提供的官方交互式界面,允许用户与 MongoDB 数据库进行交互、执行命令和操作数据库。
1.安装MongoDB Shell
[root@localhost ~]# tar xzf mongosh-2.5.0-linux-x64-openssl3.tgz
[root@localhost ~]# cd mongosh-2.5.0-linux-x64-openssl3
[root@localhost mongosh-2.5.0-linux-x64-openssl3]# cd bin/
[root@localhost bin]# cp mongosh /usr/local/bin/
[root@localhost bin]# cp mongosh_crypt_v1.so /usr/local/lib/
2.验证MongoDB Shell
[root@localhsot bin]# mongosh
Current Mongosh Log ID: 680a15327aa1c07b1b26ff
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.5.0
Using MongoDB: 8.0.8
Using Mongosh: 2.5.0For mongosh info see:
The server generated these startup warnings when booting
2025-04-24T18:22:54.368+08:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See Production Notes for Self-Managed Deployments - Database Manual - MongoDB Docs
2025-04-24T18:22:55.892+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
2025-04-24T18:22:55.892+08:00: You are running this process as the root user, which is not recommended2025-04-24T18:22:55.892+08:00: This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning
2025-04-24T18:22:55.892+08:00: Soft rlimits for open file descriptors too low
2025-04-24T18:22:55.892+08:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
2025-04-24T18:22:55.892+08:00: We suggest setting the contents of sysfsFile to 0.
2025-04-24T18:22:55.892+08:00: We suggest setting swappiness to 0 or 1, as swapping can cause performance problems.test>
四.数据库管理
1.查看数据库列表
要查看当前MongoDB实例中所有数据库的列表,可以用show dbs命令
>show dbs
要查看当前正在使用的数据库,可以用db命令
>db
2.创建数据库
test> use runoob
switched to db runoob
runoob> db
runoob
runoob>
runoob> show dbs
admin 40.00 KiB
config 60.00 KiB
local 40.00 KiB
runoob>
插入一条命令会显示你创建的列表
runoob> db.runoob.insertOne({"name":"zhangsan"})
{
acknowledged: true,
insertedId: ObjectId('680a18f4277aa1c07b1b2700')
}
runoob> show dbs
admin 40.00 KiB
config 60.00 KiB
local 40.00 KiB
runoob 40.00 KiB
runoob>
3.删除数据库
如果你要删除数据库,可以使用db.dropDatabase()
runoob>use test
test>db.dropDatabase()
4. 默认数据库
MongoDB 中默认的数据库为 test,如果您没有创建新的数据库,数据将存放在 test 数据库中。
当您通过 shell 连接到 MongoDB 实例时,如果未使用 use 命令切换到其他数据库,则会默认使用 test 数据库。
例如,在启动 MongoDB 实例并连接到 MongoDB shell 后,如果您开始插入文档而未显式指定数据库,MongoDB 将默认使用 test 数据库。
5. 系统内置数据库
在 MongoDB 中,admin、config 和 local 是三个特殊的系统内置数据库
admin 数据库:存储所有数据库的用户身份信息和全局权限(如 root 用户)。用户必须通过 admin 数据库认证后才能执行跨库管理操作。
config 数据库:仅在分片集群环境中存在。存储分片信息、块(chunk)分布、集合分片策略等关键元数据。
local 数据库:存储当前节点的副本集状态、操作日志(oplog)等本地数据。数据不会被复制到其他节点,仅存在于当前实例。
五.集合管理
1.查看集合
查看当前库已有集合,可以使用show collections命令
>show collections
2.创建集合
db.createCollection("myComplexCollection", { capped: true, size: 10485760, max: 5000, validator: { $jsonSchema: { bsonType: "object", required: ["name", "email"], properties: { name: { bsonType: "string", description: "必须为字符串且为必填项" }, email: { bsonType: "string", pattern: ".*@.*$", description: "必须为有效的电子邮件地址" } } }}, validationLevel: "strict", validationAction: "error", storageEngine: { wiredTiger: { configString: "block_compressor=zstd" } }, collation: { locale: "en", strength: 2 } });
> use test switched to db test > db.createCollection("runoob") { "ok" : 1 }
3.更新集合名
db.adminCommand({ renameCollection: "test.oldCollection", to: "test.newCollection" });
db.adminCommand({ renameCollection: "test.oldCollection", to: "production.newCollection" });
4.删除集合
>db.kgc.drop()
六.文档操作
1.插入文档
当个文档插入:insertOne()
db.myCollection.insertOne({ name: "Alice", age: 25, city: "New York" }); { "acknowledged": true, "insertedId": ObjectId("60c72b2f9b1d8b5a5f8e2b2d") }
2.insertMany()
db.myCollection.insertMany([ { name: "Bob", age: 30, city: "Los Angeles" }, { name: "Charlie", age: 35, city: "Chicago" }]); 返回结果: { "acknowledged": true, "insertedIds": [ ObjectId("60c72b2f9b1d8b5a5f8e2b2e"), ObjectId("60c72b2f9b1d8b5a5f8e2b2f") ] }
2.查询文档
查找所有文档
>db.myCollection.find();
查找当个文档
>db.myCollection.findOne({name:"bob"});
3.删除文档
deleteOne()方法用于删除匹配过滤器的单个文档
>db.myCollection.deleteOne({name:"bob"});
deleteMany()方法用于删除所有匹配过滤器的文档
> db.myCollection.deleteMany({name:"Alice"})
4.更新文档
插入测试数据
>db.myCollection.insertMany([{ name: "Alice",age: 25,city: "Los Angeles",statu s: "inactive" },{ name: "Bob",age: 30,city: "Los Angeles",status: "active" }, { name: "Charlie",age: 35,city: "Chicago",status: "active"}]);
1.updateOne()用于更新单个文档
>db.myCollection.updateOne( { name: "Alice" }, // 过滤条件 { $set: { age: 26 } }, // 更新操作 { upsert: false } // 可选参数 );
2.updateMany()用于匹配所有文档
db.myCollection.updateMany( { age: { $lt: 30 } }, // 过滤条件 { $set: { status: "active" } }, // 更新操作 { upsert: false } // 可选参数 );
七.MongoDB备份与恢复
1.安装备份与恢复命令
[root@localhost ~]#rpm -ivh mongodb-database-tools-rhel70-x86_64-100.12.0.rpm
2.MongoDB数据备份
[root@localhost ~]# mongodump 2025-04-25T22:44:21.307+0800 writing admin.system.version to dump/admin/system.version.bson 2025-04-25T22:44:21.307+0800 done dumping admin.system.version (1 document) 2025-04-25T22:44:21.308+0800 writing mydb.myCollection to dump/mydb/myCollection.bson 2025-04-25T22:44:21.308+0800 writing test.myComplexCollection to dump/test/myComplexCollection.bson 2025-04-25T22:44:21.310+0800 writing test.myCollection to dump/test/myCollection.bson 2025-04-25T22:44:21.313+0800 done dumping test.myCollection (3 documents) 2025-04-25T22:44:21.313+0800 done dumping test.myComplexCollection (0 documents) 2025-04-25T22:44:21.334+0800 done dumping mydb.myCollection (3 documents) [root@localhost ~]# ls dump
3. MongoDB数据恢复
[root@localhost ~]# mongorestore 2025-04-25T22:50:28.111+0800 using default 'dump' directory 2025-04-25T22:50:28.111+0800 preparing collections to restore from 2025-04-25T22:50:28.111+0800 don't know what to do with file "dump/prelude.json", skipping... 2025-04-25T22:50:28.111+0800 reading metadata for mydb.myCollection from dump/mydb/myCollection.metadata.json 2025-04-25T22:50:28.111+0800 reading metadata for test.myCollection from dump/test/myCollection.metadata.json 2025-04-25T22:50:28.111+0800 reading metadata for test.myComplexCollection from dump/test/myComplexCollection.metadata.json 2025-04-25T22:50:28.125+0800 restoring test.myCollection from dump/test/myCollection.bson 2025-04-25T22:50:28.134+0800 restoring mydb.myCollection from dump/mydb/myCollection.bson 2025-04-25T22:50:28.136+0800 finished restoring test.myCollection (3 documents, 0 failures) 2025-04-25T22:50:28.140+0800 restoring test.myComplexCollection from dump/test/myComplexCollection.bson 2025-04-25T22:50:28.144+0800 finished restoring mydb.myCollection (3 documents, 0 failures) 2025-04-25T22:50:28.151+0800 finished restoring test.myComplexCollection (0 documents, 0 failures) 2025-04-25T22:50:28.151+0800 no indexes to restore for collection mydb.myCollection 2025-04-25T22:50:28.151+0800 no indexes to restore for collection test.myCollection 2025-04-25T22:50:28.151+0800 no indexes to restore for collection test.myComplexCollection 2025-04-25T22:50:28.151+0800 6 document(s) restored successfully. 0 document(s) failed to restore.