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. ( 😀 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

mongoshellinstance1

After that with following commands I create a database with one collection.

use csampledb1
db.csamplecol1.save({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.

db.copyDatabase("csampledb1","csampledb2","localhost:9990")

mongoshellinstance2

Syntax of this function is like below. There are two arguments which I didn’t use.

db.copyDatabase(fromdb, todb, fromhost, username, password)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s