2024-09-15|閱讀時間 ‧ 約 5 分鐘

MongoRestore 快速介紹

raw-image

👨‍💻簡介

上一篇介紹了 mongodump,拿來將我們資料庫的檔案備份到本地,這次則是要來介紹 mongorestore,將本地的資料還原到指定的資料庫。

🔰基礎介紹

什麼是 MongoRestore?

mongorestore 是 MongoDB 提供的一個命令行工具,用於將先前使用 mongodump 產生的備份檔案恢復到資料庫中,支援 BSON 格式的資料恢復。

MongoRestore 主要功能

  • 恢復資料庫: 可以將備份的整個資料庫恢復。
  • 恢復集合(collection): 可以指定恢復特定的集合。
  • 從遠端伺服器恢復: 可以從遠端的 MongoDB 伺服器恢復資料。

Mongorestore 優缺點

優點

  1. 簡單易用:簡單的命令行操作即可完成資料還原。
  2. 支援大規模資料恢復:可以高效處理大型資料集。
  3. 支援各種平台:跨平台使用,不限作業系統。

缺點

  1. 相對耗時:對於大型資料庫,還原時間可能較長。
  2. 空間需求:恢復操作需要足夠的磁碟空間。

🎯setup

基本指令

  • 恢復整個資料庫

語法:

mongorestore --db <database_name> <path_to_backup_directory>

範例:

mongorestore --db mydatabase /path/to/backup
  • 恢復特定集合(collection)

語法:

mongorestore --db <database_name> --collection <collection_name> <path_to_collection_backup>

範例:

mongorestore --db mydatabase --collection mycollection /path/to/backup/mycollection.bson
  • 恢復到特定目錄

語法:

mongorestore --db <database_name> --dir <path_to_backup_directory>

範例:

mongorestore --db mydatabase --dir /path/to/backup
  • 從遠端 MongoDB 伺服器恢復

語法:

mongorestore --host <mongo_host_or_ip> \
--port <port> \
--db <database_name> \
--username <username> \
--password <password> \
--authenticationDatabase <auth_database> <path_to_backup_directory>

使用 URI:

mongorestore \
--uri mongodb://<username>:<password>@<mongo_host_or_ip>:<port>/<database_name>?authSource=<auth_database> \
<path_to_backup_directory>

範例:

mongorestore \
--host mongodb.example.com \
--port 27017 \
--db mydatabase \
--username mongo_user \
--password mongo_pass \
--authenticationDatabase mydatabase

常用參數

  • --uri=<connectionString>

指定 MongoDB 連線 URI

  • --host=<hostname>:<port>-h=<hostname>:<port>

指定連線 Host 和 Port,預設為 localhost:27017

  • --username=<username>-u=<username>

指定連線的使用者名稱

  • --password=<password>-p=<password>

指定連線的密碼

  • --authenticationDatabase=<dbname>

指定身份驗證的資料庫

  • --db=<database>-d=<database>

指定要恢復的資料庫,如果不指定,會恢復所有資料庫

  • --collection=<collection>-c=<collection>

指定要恢復的集合,如果不指定集合,會恢復指定資料庫的所有集合

📚Reference

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.