[MongoDB] How to use db.runCommand( { cloneCollection } )

Tadashi Shigeoka ·  Tue, July 14, 2015

I’ll introduce how to use db.runCommand( { cloneCollection } ) to copy collections in MongoDB.

MongoDB | モンゴディービー

Assume there are two mongod instances running: host: targethost1, port: 27017 and host: currenthost, port: 27018.

With the following query, you can copy documents from the users collection in the targetDb database on targethost1:27017 where verified_at is not null to currentDb with the same collection name.

mongo --host currenthost --port 27018 currentDb

var query = { verified_at : { $ne : null } };
db.runCommand( { cloneCollection: 'targetDb.users', from: 'targethost1:27017', query : query } );

If you want to change the copied collection name, you can use renameCollection.

That’s all from the Gemba.