一.什么是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.