How to Migrate MongoDB to a New Server
Adam C. |

Recently I migrated MongoDB (over 2GB) from a cheap server hosted on Hudson Valley Host to a better server hosted on Digital Ocean to improve the performance.

Photo by Ray Hennessy on Unsplash

Servers Specs

  • Old: Ubuntu 16.04 / 4G Memory /  4vCPUs E3-1240 V2 @ 3.40GHz / MongoDB 3.6.4
  • New: Ubuntu 20.04 / 8G Memory  / 4vCPUs E5-2650 v4 @ 2.20GHz / MongoDB 4.4

Install MongoDB

It's pretty straightforward by following the docs on MongoDB official website:

Note that: By default, MongoDB has no default user or password, and you can only access them via localhost. But very likely, you would need to enable access control (i.e., auth) and create a user to access the databases. 

Create DB User

Right after you install the MongoDB, you should be able to log in Mongo Shell, by running the command “mongo” via SSH terminal. And then enter the following command:

use admin
    user: "dbUser",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]

Note that I assign the user userAdminAnyDatabase role, which gives the user the ability to create users and assign arbitrary roles to them.  It sounds like a superuser, but it's not. To be a superuser or root user, you have to assign the following roles:

Export Remote Database

Run the following command to dump the existing remote database:

mongodump  --host "REMOTE_DB_HOST" --username "REMOTE_DB_USERNAME" --password "REMOTE_DB_PASS" --authenticationDatabase "admin" --db "DB_NAME" --out "backup"


  1.  ‘admin’ is the default authenticationDatabase,  you may use a different one.
  2. use “--out” instead of “--archive” as some other tutorial mentioned, and “backup” is the folder name where I save the dump files

Import dumped MongodDB

In the folder having ‘backup’ subfolder, run the following command:

mongorestore backup/

Enable Auth and Remote Access


Now it's time to enable auth and remote access. It can be configured in the mongod.conf (by default: it's under /etc/mongod.conf.) Run ‘vim /etc/mongod.conf’, and then modify the following lines:

  port: 27017
# change bindIP to all IPV4 addresses, otherwise mongod only listens to
# ...
# uncomment security and enable authorization
  authorization: enabled

By default,  Ubuntu does not enable UFW (Uncomplicated Firewall) If you use it, then you add the remote server IP the whitelist using the following command:

sudo ufw allow from remote_server_ip to any port 27017