MongoDB Copy Database
mongodump
and mongorestore
, and Node.js (Mongoose).1. Copy a Database Using MongoDB Shell
MongoDB does not have a built-in copyDatabase()
function in modern versions. Instead, you must manually copy collections.
A. Open MongoDB Shell
Start the MongoDB shell:
B. Select the Source Database
C. Copy Each Collection to the Target Database
To copy the posts
collection from sourceDB
to targetDB
:
✅ Verify the copy:
✅ Output:
The the posts
collection has been copied to targetDB
.
2. Copy a Database Using mongodump
and mongorestore
This method exports the database and then restores it into a new one.
A. Dump (Export) the Source Database
✅ This creates a backup in /backup/sourceDB/
.
B. Restore (Import) to a New Database
✅ Verify the copy:
✅ Expected Output:
3. Copy a Database Using Node.js (Mongoose)
A. Install Dependencies
B. Create a Script to Copy All Collections
Create copyDatabase.js
:
C. Run the Script
✅ Output:
4. Summary
✔ Copied collections manually using MongoDB Shell ($out
).
✔ Used mongodump
and mongorestore
for full database copying.
✔ Created a Node.js script to copy all collections programmatically.
5. Next Steps
🔹 Schedule automatic backups for better data safety.
🔹 Use authentication when copying databases between servers.
🔹 Optimize large database copies using indexes.
Would you like help setting up automated backups or cloud migrations? 🚀