[MongoDB] db.runCommand( { cloneCollection } ) の使い方

MongoDB で collection をコピーする db.runCommand( { cloneCollection } ) の使い方をご紹介します。

MongoDB | モンゴディービー

host: targethost1, port: 27017 と host: currenthost, port: 27018 で mongod instance が2つ立ち上がっている状態とします。

以下のようなクエリで targethost1:27017 の targetDb database にある users collection から verified_at が null ではない document を currentDb に同じ collection 名でコピーできます。

mongo --host currenthost --port 27018 currentDb
 
var query = { verified_at : { $ne : null } };
db.runCommand( { cloneCollection: 'targetDb.users', from: 'targethost1:27017', query : query } );

コピーした collection 名を変更したい場合は renameCollection でできます。

以上です。