2016年もいよいよカウントダウンですね。残すところあと5日です。
今日のお悩み
mongodbのcollectionを別dbへのcollectionに移動させたい
要はexport/importですね。
解決
mongoexport と mongoimportを使います
$ mongoexport --db old_db --collection users --out /tmp/users.json
2016-12-26T05:22:27.667+0000 connected to: localhost
2016-12-26T05:22:27.671+0000 exported 26 records
- (例)新しいdbへインポート
$ mongoimport --db new_db --collection users --file /tmp/users.json
2016-12-26T05:24:18.118+0000 connected to: localhost
2016-12-26T05:24:18.159+0000 imported 26 documents
注意
これらのコマンドは、プロダクション環境のフルインスタンスのバックアップ用途としては使わないように、ということですね。
mongodbのバックアップにはmongodumpを戻すのはmongorestoreで
$ mongodump --archive=/tmp/test.20150715.gz --gzip --db test
2016-12-26T05:44:08.920+0000 writing test.users to archive '/tmp/test.20150715.gz'
2016-12-26T05:44:08.928+0000 writing test.rooms to archive '/tmp/test.20150715.gz'
2016-12-26T05:44:08.930+0000 done dumping test.users (26 documents)
2016-12-26T05:44:08.931+0000 done dumping test.rooms (6 documents)
- (例)mongorestore
$ mongorestore --gzip --archive=/tmp/test.20150715.gz --db test
2016-12-26T05:47:04.805+0000 creating intents for archive
2016-12-26T05:47:04.844+0000 reading metadata for test.users from archive '/tmp/test.20150715.gz'
2016-12-26T05:47:04.870+0000 restoring test.users from archive '/tmp/test.20150715.gz'
2016-12-26T05:47:04.890+0000 reading metadata for test.rooms from archive '/tmp/test.20150715.gz'
2016-12-26T05:47:04.902+0000 restoring test.rooms from archive '/tmp/test.20150715.gz'
2016-12-26T05:47:04.919+0000 restoring indexes for collection test.rooms from metadata
2016-12-26T05:47:04.919+0000 restoring indexes for collection test.users from metadata
2016-12-26T05:47:04.919+0000 finished restoring test.users (26 documents)
2016-12-26T05:47:04.919+0000 finished restoring test.rooms (6 documents)
2016-12-26T05:47:04.920+0000 done
注意
mongodump only captures the documents in the database.
The resulting backup is space efficient, but mongorestore or mongod must rebuild the indexes after restoring data.