Kim Spasaro

Migrating AWS EC2 Database to MongoDB Atlas

November 11, 2016 ,

June saw the release of MongoDB Atlas, a MongoDB hosting service built by the makers of MongoDB itself. This “database as a service” has some pretty cool out-of-the-box benefits, including:

Luckily, migrating replica sets from AWS EC2 instances isn’t too hard.

Step 1: Create a MongoDB Atlas Cluster

Add a new cluster on MongoDB.

Step 2: Export Database on EC2 Instance

The first step is to export the Mongo databases on your EC2 instance using mongodump. Login to AWS, choose your EC2 instance, and click “Connect” to get the command to ssh into your EC2 instance. Then run the following command, replacing the host argument¬†with the public DNS address for your EC2 instance.

mongodump --host ec2-12-345-67-8.compute-1.amazonaws.com --port 27017

This will create a binary data dump that you can use to import the data to another Mongo database. If you run the ls command you should see the exported file, called dump.

Step 3: Whitelist Your EC2 Instance on MongoDB Atlas

Next, add the IP address for your EC2 instance to your IP whitelist on MongoDB Atlas. This will let your EC2 instance connect to Atlas so that you can import the data file to your specified cluster.

Step 4: Import Database to MongoDB Atlas Instance

Run the following command from your EC2 instance, replacing the host argument with the URI for the primary member in your replica set (most likely the node containing shard-00-00). Omitting the -p flag will prompt you to enter your password without exposing it in your terminal’s command history.

mongorestore --ssl --host cluster0-shard-00-00-abcde.mongodb.net --port 27017 -u username dump

Make sure that the username you’re connecting with has Atlas write privileges.