MongoDB數據遷移至Ubuntu的步驟
read/readWrite)執行導出操作;若遷移過程中需保證數據一致性,建議停止業務寫入或在低峰期操作。sudo apt update && sudo apt install mongodb安裝,默認版本可能較舊,建議通過MongoDB官方倉庫安裝最新穩定版)。在源MongoDB服務器上執行以下命令,將指定數據庫導出到本地目錄(如/home/user/mongo_dump):
mongodump --host <源數據庫IP> --port <源數據庫端口> --username <用戶名> --password <密碼> --authenticationDatabase admin --db <源數據庫名> --out /home/user/mongo_dump
--host/--port指定源數據庫地址;--username/--password為認證信息;--authenticationDatabase為認證數據庫(通常為admin);--db指定要導出的數據庫;--out指定導出目錄。testdb數據庫到/home/user/mongo_dump):mongodump --host 127.0.0.1 --port 27017 --username admin --password 123456 --authenticationDatabase admin --db testdb --out /home/user/mongo_dump
使用scp(安全復制)將導出的備份目錄傳輸到Ubuntu服務器(如ubuntu@192.168.1.100)的目標目錄(如/home/ubuntu/mongo_dump):
scp -r /home/user/mongo_dump ubuntu@192.168.1.100:/home/ubuntu/mongo_dump
-r表示遞歸復制整個目錄;ubuntu@192.168.1.100為目標服務器的用戶名和IP;/home/ubuntu/mongo_dump為目標目錄。登錄Ubuntu服務器,執行以下命令將備份數據導入到目標MongoDB實例(默認端口27017):
mongorestore --host localhost --port 27017 --username <目標數據庫用戶名> --password <目標數據庫密碼> --authenticationDatabase admin /home/ubuntu/mongo_dump/<源數據庫名>
--host/--port指定目標數據庫地址;--username/--password為目標數據庫認證信息;/home/ubuntu/mongo_dump/<源數據庫名>為備份目錄路徑(如/home/ubuntu/mongo_dump/testdb)。testdb數據庫):mongorestore --host localhost --port 27017 --username admin --password 123456 --authenticationDatabase admin /home/ubuntu/mongo_dump/testdb
若源數據庫與Ubuntu目標數據庫版本差異較大或需跨系統遷移,可使用JSON/CSV格式遷移:
在源服務器上執行以下命令,導出指定集合(如users)到JSON文件:
mongoexport --host <源數據庫IP> --port <源數據庫端口> --username <用戶名> --password <密碼> --authenticationDatabase admin --db <源數據庫名> --collection <集合名> --out /home/user/users.json
--collection指定要導出的集合;--out指定導出文件路徑。testdb數據庫的users集合到JSON):mongoexport --host 127.0.0.1 --port 27017 --username admin --password 123456 --authenticationDatabase admin --db testdb --collection users --out /home/user/users.json
使用scp將JSON文件傳輸到Ubuntu服務器的目標目錄:
scp /home/user/users.json ubuntu@192.168.1.100:/home/ubuntu/users.json
登錄Ubuntu服務器,執行以下命令將JSON文件導入到目標MongoDB集合:
mongoimport --host localhost --port 27017 --username <目標數據庫用戶名> --password <目標數據庫密碼> --authenticationDatabase admin --db <目標數據庫名> --collection <目標集合名> --file /home/ubuntu/users.json --jsonArray
--file指定導入文件路徑;--jsonArray表示文件為JSON數組格式(若為單條記錄可省略)。testdb數據庫的users集合):mongoimport --host localhost --port 27017 --username admin --password 123456 --authenticationDatabase admin --db testdb --collection users --file /home/ubuntu/users.json --jsonArray
mongo --host localhost --port 27017),切換至目標數據庫(use testdb),查看集合是否存在(show collections),并查詢數據(db.users.find().pretty())。db.<集合名>.countDocuments())、關鍵字段值(如_id、name),確保數據無遺漏或錯誤。db.<集合名>.createIndex({字段: 1}))。db.createUser({user: 'app_user', pwd: 'secure_pwd', roles: [{role: 'readWrite', db: 'testdb'}]})),避免使用admin賬戶直接訪問。/etc/mongod.conf)中的security.authorization為enabled,重啟服務(sudo systemctl restart mongod)。