In this article, we will see how to copy a collection from one database to another in MongoDB. As a maintenance activity its routine task to copy a collection from one database to another database in MongoDB Server.
Syntax to copy a collection from one database to another in MongoDB:
db.collection_name.find().forEach(function(d){ db.getSiblingDB('target_db')['collection_in_target'].insert(d); });
Where
collection_name is source collection to be copied
target_db is the target database to copy a collection to.
collection_in_target will be name in target database.
Example to copy a collection from one database to another in MongoDB:
1. Copy collection ‘students’ from the database ‘r2schools’ to database ‘m201’ keep the same collection name ‘students’.
use r2schools db.students.find().forEach(function(d){ db.getSiblingDB('m201')['students'].insert(d); });
2. Lets verify in target database ‘m201’, this collection moved successfully or not.
use m201 show collections