MongoDBで特定のコレクションをダンプしてリストアする

MongoDBで、あるデータベースのあるコレクションをダンプしてリストアする方法を調べたので、纏めておきます。


環境

  • Ubuntu 16.04
  • MongoDB 3.4.2

ダンプ

ダンプには、mongodumpを使う。

次の例は、db1というデータベースのcollection1というコレクションをdumpディレクトリにダンプする。

mongodumpo -d db1 -c collection1 --out dump

試しに、dump_restore_testというデータベースのarticlesというドキュメントが1件のコレクションに対してやってみる。

$ mongodump -d dump_restore_test -c articles --out dump
2017-02-28T03:23:56.232+0000 writing dump_restore_test.articles to
2017-02-28T03:23:56.234+0000 done dumping dump_restore_test.articles (1 document)

と、こんなログが出力されて、dumpディレクトリに、

$ tree dump
dump
└── dump_restore_test
  ├── articles.bson
  └── articles.metadata.json

1 directory, 2 files

が出力された。

リストア

リストアには、mongorestoreを使う。

次の例は、db1というデータベースのcollection1というコレクションにmongodumpでダンプしたbsonをリストアする例。

mongorestore --drop -d db1 -c collection1 path_to_bson_file.bson

--dropオプションをつけると、リストア前にリストア先のコレクションが削除される。

dump元のコレクションとrestore先のコレクションが全く同じ場合、--dropオプションをつけないと、キー重複エラーが発生する。

試しに、上述のarticlesコレクションにarticles.bsonをリストアしてみる。

$ mongorestore --drop -d dump_restore_test -c articles dump/dump_resotre_test/article.bson
2017-02-28T04:11:04.480+0000 checking for collection data in dump/dump_restore_test/articles.bson
2017-02-28T04:11:04.487+0000 reading metadata for dump_restore_test.articles from dump/dump_restore_test/articles.metadata.json
2017-02-28T04:11:04.562+0000 restoring dump_restore_test.articles from dump/dump_restore_test/articles.bson
2017-02-28T04:11:04.636+0000 no indexes to restore
2017-02-28T04:11:04.636+0000 finished restoring dump_restore_test.articles (1 document)
2017-02-28T04:11:04.637+0000 done

1ドキュメントがリストアされた。


今回は特定のコレクションのみを扱う場合について纏めましたが、他の状況についてもあらためて調べて纏めてみたいと思います。