🗄️ MongoDB

靈活的文件型 NoSQL 資料庫

MongoDB 以 BSON 格式儲存 JSON 文件,Schema-less 設計靈活,支援水平分片與複製集,適合結構頻繁變動或半結構化資料的場景。

安裝(Ubuntu 22.04)

$ curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
  sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \
  https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \
  sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt update && sudo apt install -y mongodb-org
sudo systemctl enable --now mongod
$ mongosh    # 連線到本機 MongoDB

啟用認證(生產環境必做)

$ # 1. 先在無認證狀態下建立管理員
mongosh
use admin
db.createUser({
  user: "admin",
  pwd: "安全密碼",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
})
$ # 2. 啟用認證
sudo vim /etc/mongod.conf
security:
  authorization: enabled
$ sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin

常用操作

// 建立資料庫(首次插入資料時自動建立)
use myapp

// 建立應用程式使用者
db.createUser({
  user: "appuser",
  pwd: "密碼",
  roles: [ { role: "readWrite", db: "myapp" } ]
})

// 插入文件
db.users.insertOne({ name: "Alice", email: "alice@example.com", createdAt: new Date() })

// 查詢
db.users.find({ name: "Alice" })
db.users.find({}).sort({ createdAt: -1 }).limit(10)

// 更新
db.users.updateOne({ name: "Alice" }, { $set: { email: "new@example.com" } })

// 刪除
db.users.deleteOne({ name: "Alice" })

// 建立索引(提升查詢效能)
db.users.createIndex({ email: 1 }, { unique: true })

備份與還原

$ # 備份單一資料庫
mongodump -u admin -p 密碼 --authenticationDatabase admin \
  --db myapp --out /backup/$(date +%Y%m%d)

# 備份所有資料庫
mongodump -u admin -p 密碼 --authenticationDatabase admin \
  --out /backup/$(date +%Y%m%d)
$ # 還原
mongorestore -u admin -p 密碼 --authenticationDatabase admin \
  --db myapp /backup/20260520/myapp

常用設定(/etc/mongod.conf)

net:
  port: 27017
  bindIp: 127.0.0.1    # 只允許本機,遠端改為 0.0.0.0

storage:
  dbPath: /var/lib/mongodb
  wiredTiger:
    engineConfig:
      cacheSizeGB: 1    # WiredTiger 快取(預設為 RAM 的 50%)

operationProfiling:
  slowOpThresholdMs: 100  # 記錄超過 100ms 的慢查詢