MongoDB 運用に役立つ基本コマンド集

データベース操作

起動

su - mongo
mongod -f /etc/mongodb/mongodb27017.conf

ログイン

mongo admin -u root -p --port=27017

シャットダウン

mongod --shutdown --dbpath=/mongodata/db

データベース削除

use target_db;
db.dropDatabase();

コレクション削除

use target_db;
db.target_collection.drop();

接続テスト

/mongodb3.6.17/bin/mongo 192.168.1.10:27017 -u app_user -p --authenticationDatabase=admin

サンプルデータ取得

db.oplog.rs.find().limit(10).pretty();

ユーザーと権限管理

rootユーザー作成

use admin;
db.createUser({
  user: "superuser",
  pwd: "securePass!2024",
  roles: [{ role: "root", db: "admin" }]
});

管理ユーザー追加

use admin;
db.createUser({
  user: "admin_ops",
  pwd: "opsPass#2024",
  roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
});

一般ユーザー作成(全DB読み取り)

use admin;
db.createUser({
  user: "readonly_user",
  pwd: "roPass$2024",
  roles: [{ role: "readAnyDatabase", db: "admin" }]
});

特定DB向け業務アカウント

use admin;
db.createUser({
  user: "app_writer",
  pwd: "writePass%2024",
  roles: [{ role: "readWrite", db: "production_db" }]
});

認証方式指定(SCRAM-SHA-1)

use admin;
db.createUser({
  user: "legacy_user",
  pwd: "legacyPass",
  roles: [{ role: "read", db: "reporting" }],
  mechanisms: ["SCRAM-SHA-1"]
});

全ユーザー一覧取得

use admin;
db.system.users.find({}, { user: 1, db: 1 }).pretty();

現在DBのユーザー確認

use admin;
db.getUsers();

権限付与

db.grantRolesToUser("app_user", [
  { role: "dbOwner", db: "service_a" },
  { role: "read", db: "analytics" }
]);

権限剥奪

db.revokeRolesFromUser("temp_user", [
  { role: "clusterMonitor", db: "admin" }
]);

ユーザー削除

use admin;
db.dropUser("obsolete_user");

パスワード変更

use admin;
db.changeUserPassword("target_user", "newSecurePass!2024");

IP制限(ホワイトリスト)

新規ユーザー作成時にIP制限設定

use admin;
db.createUser({
  user: "restricted_user",
  pwd: "ipRestrictedPass",
  roles: [{ role: "readWrite", db: "restricted_db" }],
  authenticationRestrictions: [{
    clientSource: ["203.0.113.0/24"],
    serverAddress: ["198.51.100.0/24"]
  }]
});

既存ユーザーへのIP制限追加

db.updateUser("existing_user", {
  authenticationRestrictions: [{
    clientSource: ["192.0.2.0/24"],
    serverAddress: ["198.51.100.0/24"]
  }]
});

監視機能

Free Monitoring有効化

db.enableFreeMonitoring();

Free Monitoring無効化

db.disableFreeMonitoring();

インデックス操作

インデックス一覧表示

db.products.getIndexes();

インデックスサイズ確認

db.products.totalIndexSize();

全インデックス削除

db.products.dropIndexes();

特定インデックス削除

db.products.dropIndex("name_1");

単一フィールドインデックス作成

db.products.createIndex({ sku: 1 });

複合インデックス作成

db.products.createIndex({ category: 1, price: -1 });

バックグラウンドでインデックス作成

db.orders.createIndex({ status: 1, created_at: -1 }, { background: true });

ユニークインデックス作成(バックグラウンド)

db.users.createIndex({ email: 1 }, { background: true, unique: true });

コレクションのドキュメント数

db.transactions.count();

ストレージ使用量確認

db.transactions.dataSize();      // 実データサイズ
db.transactions.storageSize();   // 割り当て済みストレージ
db.transactions.totalSize();     // データ+インデックス合計

レプリカセット・シャーディング

oplogサイズ確認

use local;
db.oplog.rs.stats().maxSize;

oplogサイズ変更(10GB)

use admin;
db.adminCommand({ replSetResizeOplog: 1, size: 10240 });

セカンダリノードでのクエリ許可

rs.slaveOk();

レプリケーション遅延確認

rs.printSlaveReplicationInfo();

レプリカセットステータス

rs.status();

プライマリ降格(60秒)

rs.stepDown();

シャーディングクラスタ状態確認

sh.status();

システム負荷監視(mongostat)

mongostat -u monitor_user --authenticationDatabase=admin --port=27017

データインポート・エクスポート

CSV形式でエクスポート

mongoexport --host=localhost --port=27017 -u export_user -p 'pass' \
--authenticationDatabase=admin --db sales -c orders --out orders.csv \
-q '{"status":"completed"}' --fields="orderId,customerId,total"

JSON形式でエクスポート

mongoexport --authenticationDatabase=admin -u export_user -d analytics -c events \
--query='{"date": {"$gte": "2024-01-01"}}' -o events.json

バックアップとリストア

# バックアップ
mongodump --host=localhost --port=27017 -u backup_user -p 'pass' \
--authenticationDatabase=admin -d critical_db -o /backup/mongo

# リストア
mongorestore --host=localhost --port=27018 -u restore_user -p 'pass' \
--authenticationDatabase=admin -d restored_db --dir /backup/mongo/critical_db

クエリ最適化

実行計画確認

db.users.find({ email: "test@example.com" }).explain("executionStats");

プロファイリング有効化

db.setProfilingLevel(1, { slowms: 50 });
db.system.profile.find().sort({ ts: -1 }).limit(5).pretty();

接続URIフォーマット

mongodb://username:password@host1:27017,host2:27017/database?replicaSet=myRepl&authSource=admin

日時処理

現在時刻取得(ローカル)

new Date();

ObjectIdから作成時刻取得

ObjectId("507f1f77bcf86cd799439011").getTimestamp();

認証エラー対応

SCRAM-SHA-256関連エラーが発生する場合、明示的にmechanisms: ["SCRAM-SHA-1"]を指定してユーザーを作成する必要があります。

db.createUser({
  user: "compat_user",
  pwd: "password123",
  roles: [{ role: "read", db: "test" }],
  mechanisms: ["SCRAM-SHA-1"]
});

タグ: MongoDB データベース管理 レプリカセット シャーディング インデックス最適化

6月28日 21:48 投稿