MongoDB在Ubuntu上的數據遷移流程及注意事項
在Ubuntu系統上遷移MongoDB數據,核心是通過官方工具鏈(mongodump/mongorestore、mongoexport/mongoimport)實現數據的高效轉移,同時需關注環境準備、數據一致性及權限配置等關鍵環節。以下是具體操作指南:
環境檢查
確保Ubuntu系統已安裝MongoDB(可通過mongod --version
驗證服務端,mongo --version
驗證客戶端)。若未安裝,使用以下命令安裝最新穩定版:
sudo apt update
sudo apt install -y mongodb
工具安裝
若需使用mongodump
/mongorestore
(二進制備份工具)或mongoexport
/mongoimport
(JSON/CSV格式工具),需額外安裝mongodb-org-tools
包:
sudo apt install -y mongodb-org-tools
權限確認
確保源數據庫與目標數據庫的用戶具備**讀(source)和寫(target)**權限。例如,源數據庫用戶需有read
角色,目標數據庫用戶需有readWrite
角色。
適用場景:全量/增量遷移、需要保留索引結構、遷移大量數據。
步驟1:備份源數據庫
使用mongodump
導出源數據庫(如mydb
)到指定目錄(如/tmp/mongodump
):
mongodump --uri="mongodb://source_host:27017" --db=mydb --out=/tmp/mongodump
若源數據庫需要認證,添加--username
、--password
參數:
mongodump --uri="mongodb://username:password@source_host:27017/admin" --db=mydb --out=/tmp/mongodump
步驟2:傳輸備份文件到目標Ubuntu
若源數據庫在遠程服務器,使用scp
將備份目錄復制到目標機器:
scp -r /tmp/mongodump username@target_ubuntu_ip:/tmp/
步驟3:恢復數據到目標數據庫
使用mongorestore
將備份數據導入目標數據庫(如mydb_target
),--drop
參數可先刪除目標數據庫(避免重復數據):
mongorestore --uri="mongodb://target_host:27017" --db=mydb_target --drop /tmp/mongodump/mydb
適用場景:導出為JSON/CSV格式、跨數據庫系統遷移(如MongoDB→MySQL)、小批量數據遷移。
步驟1:導出單集合(JSON格式)
使用mongoexport
導出源數據庫的mycollection
集合到mycollection.json
:
mongoexport --uri="mongodb://source_host:27017" --db=mydb --collection=mycollection --out=mycollection.json
步驟2:傳輸JSON文件到目標Ubuntu
scp mycollection.json username@target_ubuntu_ip:/tmp/
步驟3:導入單集合到目標數據庫
使用mongoimport
將JSON文件導入目標數據庫的mycollection
集合:
mongoimport --uri="mongodb://target_host:27017" --db=mydb_target --collection=mycollection --file=/tmp/mycollection.json
適用場景:無需命令行、快速遷移少量數據。
數據量核對
對比源數據庫與目標數據庫的集合數量、文檔數量是否一致:
# 源數據庫文檔數
mongo --uri="mongodb://source_host:27017" --eval "db.mydb.mycollection.countDocuments()"
# 目標數據庫文檔數
mongo --uri="mongodb://target_host:27017" --eval "db.mydb_target.mycollection.countDocuments()"
數據內容抽樣
隨機抽取部分文檔,對比源與目標數據庫的字段值是否一致:
# 源數據庫抽樣
mongo --uri="mongodb://source_host:27017" --eval "db.mydb.mycollection.findOne()"
# 目標數據庫抽樣
mongo --uri="mongodb://target_host:27017" --eval "db.mydb_target.mycollection.findOne()"
索引檢查
確認目標數據庫的索引是否與源數據庫一致:
# 源數據庫索引
mongo --uri="mongodb://source_host:27017" --eval "db.mydb.mycollection.getIndexes()"
# 目標數據庫索引
mongo --uri="mongodb://target_host:27017" --eval "db.mydb_target.mycollection.getIndexes()"
數據一致性
遷移前停止源數據庫的寫入操作(或使用--oplog
參數進行增量同步),避免遷移過程中數據變更導致不一致。
權限配置
若目標數據庫啟用了認證,需在命令中添加--authenticationDatabase=admin
參數(如mongorestore --uri="mongodb://username:password@target_host:27017/admin"
)。
網絡帶寬
大批量數據遷移時,建議使用高速網絡(如千兆以太網)或壓縮備份文件(mongodump --gzip
),減少遷移時間。
錯誤處理
若遷移過程中出現E11000 duplicate key error
(重復鍵),可使用--drop
參數刪除目標數據庫中的重復數據;若出現認證失敗,檢查用戶名、密碼及認證數據庫是否正確。
通過以上步驟,可實現MongoDB在Ubuntu系統上的高效、安全遷移。根據數據量、格式需求選擇合適的工具,能有效提升遷移效率并保證數據完整性。