Skip to main content

How to copy a Database from a MongoDB instance to another?

Some times we need to take backups or we need to copy databases to another servers for administrative purposes. But sometimes just copying files is not enough. In MongoDB Shell they support to copy database from remote instance to current one with a single command. ( :D Just like Single Click in Windows )

For this demo I made alive two instances of MongoDB from following commands.
//Instance 1
mongod --port 9990 --dbpath /data/db1
//Instance 2
mongod --port 9991 --dbpath /data/db2

In instance 1 there is a database called "csampledb1". For that I need to connect to first instance to create that database.
mongo localhost:9990


After that with following commands I create a database with one collection.
use csampledb1{id:1, name:"sample name"})

Then I log in to next MongoDB instance using MongoDB Shell.
mongo localhost:9991

Then I use single command to copy the database from instance 1 to instance 2.


Syntax of this function is like below. There are two arguments which I didn't use.
db.copyDatabase(fromdb, todb, fromhost, username, password)