Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy a database from one MongoDB server to another?

Tags:

mongodb

I have two mongodbs in different server, both start with --auth. Now I want to copy a db from one server to another.

> mongo > use admin > db.copyDatabase("mydb","mydb","another_server") 

It shows:

{ "errmsg" : "", "ok" : 0 } 

And:

> db.getLastError() null 

Seems no error, but the copy is not successful. What's the correct command to use?

like image 291
Freewind Avatar asked Mar 31 '11 03:03

Freewind


People also ask

How do I import a database into MongoDB?

To import data to a MongoDB database, you can use mongoimport to import specific collections data, or you can use mongorestore to import a binary (BSON) full database backup. The exported database file must be stored locally on the same machine as your client.


2 Answers

If you are using --auth, you'll need to include your username/password in there...

Also you must be on the "destination" server when you run the command.

db.copyDatabase(<from_db>, <to_db>, <from_hostname>, <username>, <password>); 

If all that doesn't work, you might want to try something like creating a slave of the database you want to copy ...

like image 99
Justin Jenkins Avatar answered Sep 20 '22 08:09

Justin Jenkins


Starting from Mongo version 3.2 you can do it by using mongodump/mongorestore:

mongodump  --host <from_host> --db <from_db> --archive | mongorestore --host <to_host> --archive 

Additional info could be found at:

https://docs.mongodb.com/manual/reference/program/mongodump/ https://docs.mongodb.com/manual/reference/program/mongorestore/

To make remote mongo reachable you can create ssh tunnel to it:

creates a tunnel to the remote mongodb server and tunnels it through port 27117 to the local client

ssh -fN -L 27117:localhost:27017 <remote_host>  

In this case the command to run on the local machine you want to restore to could be:

mongodump  --port 27117 --db <from_db> --archive | mongorestore --archive 
like image 27
Mike Shauneu Avatar answered Sep 19 '22 08:09

Mike Shauneu