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 server for administrative purposes. But sometimes just copying files is not enough. In MongoDB Shell, they support to copy the database from remote instance to the current one with a single command. ( :D Just like Single Click in Windows )

nn

For this demo, I made alive two instances of MongoDB from the following commands.

nn

# Instance 1  nmongod --port 9990 --dbpath /data/db1 nn# Instance 2  nmongod --port 9991 --dbpath /data/db2n

nn

In instance 1 there is a database called “csampledb1”. For that, I need to connect to the first instance to create that database.

nn

mongo localhost:9990n

nn

mongoshellinstance1

nn

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

nn

use csampledb1  ndb.csamplecol1.save({id:1, name:"sample name"})n

nn

Then I log in to next MongoDB instance using MongoDB Shell.

nn

mongo localhost:9991n

nn

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

nn

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

nn

mongoshellinstance2

nn

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

nn

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

nn

Tags

nn

    n

  • MongoDB
  • n

  • MongoDB running two instances
  • n

  • first instance
  • n

  • MongoDB Shell
  • n

  • administrative purposes
  • n

  • software
  • n

  • MongoDB copy databases
  • n

n

Proudly powered by WordPress

Discover more from Dedunu

Subscribe now to keep reading and get access to the full archive.

Continue reading