How to Copy One MongoDB Database to Another Using mongosh (Without Backup Files)
When working with multiple environments like development and production, it’s common to move data between databases. If both databases are on the same MongoDB server, you can copy all collections and documents directly using mongosh — no backup files required.
In this guide, we’ll copy:
abc-dbname-dev→abc-dbname-prod
⚠️ Warning Before You Start
This process will:
Delete existing collections in the target database
Copy all documents from the source database
Not copy indexes (data only)
Always take a backup if the target database contains important data.
Step 1: Open Mongo Shell
mongosh
Step 2: Run the Copy Script
Paste the following script into the shell:
const sourceDB = "abc-dbname-dev";
const targetDB = "abc-dbname-prod";
db.getSiblingDB(sourceDB).getCollectionNames().forEach(col => {
const from = db.getSiblingDB(sourceDB)[col];
const to = db.getSiblingDB(targetDB)[col];
print(`Copying collection: ${col}`);
to.drop(); // Remove existing collection
const docs = from.find().toArray();
if (docs.length > 0) {
to.insertMany(docs);
}
});
print("✅ Copy completed successfully");
Step 3: Verify the Data
use abc-dbname-prod
show collections
When Should You Use This Method?
This approach is perfect when:
Both databases are on the same MongoDB server
You want a quick clone of dev → prod
The database size is small to medium
You don’t need indexes copied
When NOT to Use This Method
Avoid this method if:
Your database is very large (use
mongodumpinstead)You must preserve indexes
You want to merge data instead of overwriting
Bonus: Copy Indexes Too (Optional)
If needed, indexes can also be copied using an extended script.
Conclusion
Using mongosh to copy databases is a fast and simple solution for environment synchronization during development and testing. For production-scale data migrations, however, prefer mongodump and mongorestore.
0 comments:
Post a Comment