Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy/Clone mongodb database along with its data

Tags:

mongodb

I need to copy my Mongo database along with its data. I have tried

db.copyDatabase( "Old_db", "new_db", "localhost" ) 

But the problem is it only copies a blank db, not with the previous data.

like image 606
user1795109 Avatar asked Feb 13 '13 05:02

user1795109


1 Answers

Feb 2019

since db.copyDatabase() was deprecated in v4.0, you should use mongodump and mongorestore instead:

mongodump      --host <source host:port>      --ssl      --username <username>      --password <password>      --authenticationDatabase admin      --db <sourceDbName>      --collection <collection-name> 

mongodump command will export the whole database into a local folder named dump/<sourceDbName> by default, then use mongorestore command to import to your target database:

mongorestore      --host <target host:port>      --ssl      --username <username>      --password <password>      --authenticationDatabase admin      --db <targetDbName>     --collection <collection-name>     <dump folder/file> 

Examples:

# backup the whole db (mydb-old): mongodump -h Cluster0-shard-0/sample-shard-00-00-xyz.mongodb.net:27017 \ --ssl -u user1 -p 123123 --authenticationDatabase admin \ -d mydb-old  # backup only one collection (mydb-old.users): mongodump -h Cluster0-shard-0/sample-shard-00-00-xyz.mongodb.net:27017 \ --ssl -u user1 -p 123123 --authenticationDatabase admin \ -d mydb-old -c users  # restore the whole db (mydb-old) to mydb-new: mongorestore -h Cluster0-shard-0/sample-shard-00-00-xyz.mongodb.net:27017 \ --ssl -u user1 -p 123123 --authenticationDatabase admin \ -d mydb-new dump/mydb-old  # restore only one collection (mydb-old.users) to mydb-new.users: mongorestore -h Cluster0-shard-0/sample-shard-00-00-xyz.mongodb.net:27017 \ --ssl -u user1 -p 123123 --authenticationDatabase admin \ -d mydb-new -c users dump/mydb-old/users.bson  

Find out more:

  • mongodump
  • mongorestore
like image 74
backslash112 Avatar answered Oct 17 '22 08:10

backslash112