Copy/Clone mongodb database along with its data

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)