Cloud Computing

How to Set Up MongoDB on AWS: Step-by-Step Guide

MongoDB is one of the most popular NoSQL databases used in modern web applications. If you are building an application with Node.js, Express.js, React.js, or…

D
DevByteTechnical Author
Published
7 min read0 views
How to Set Up MongoDB on AWS: Step-by-Step Guide

MongoDB is one of the most popular NoSQL databases used in modern web applications. If you are building an application with Node.js, Express.js, React.js, or Next.js, you may need a reliable cloud database to store your application data.

Amazon Web Services (AWS) provides cloud infrastructure that can host MongoDB. One of the easiest ways to use MongoDB on AWS is through MongoDB Atlas, a managed database service that supports deployment on AWS infrastructure.

In this guide, you will learn how to set up MongoDB on AWS using MongoDB Atlas, configure database security, connect MongoDB Compass, and integrate MongoDB with a Node.js application.

What Is MongoDB Atlas?

MongoDB Atlas is a fully managed cloud database service that allows developers to deploy and manage MongoDB databases without manually maintaining database servers.

You can choose AWS as your cloud provider when creating an Atlas deployment. Atlas manages much of the underlying database infrastructure, allowing you to focus on building your application.

Benefits of Using MongoDB on AWS

  • Easy deployment: Create a cloud database without manually installing MongoDB on a server.

  • Scalability: Choose appropriate database resources as your application grows.

  • Security: Configure database authentication and network access restrictions.

  • Automated backups: Use available backup options to protect important data.

  • High availability: Choose deployment configurations that support redundancy and recovery.

  • Application integration: Connect MongoDB to Node.js, Express.js, and other supported technologies.

MongoDB Atlas is particularly useful for MERN stack applications, SaaS platforms, REST APIs, and production web applications.

Prerequisites

Before setting up MongoDB on AWS, make sure you have:

  1. An active internet connection.

  2. A MongoDB Atlas account.

  3. Basic knowledge of MongoDB.

  4. MongoDB Compass installed on your computer (optional).

  5. Node.js installed if you want to connect your application.

You can create an account through the official MongoDB Atlas website.

Note: Check the current pricing and available free-tier options before creating a deployment. Free-tier eligibility and available configurations may change.

Step 1: Create a MongoDB Atlas Account

First, open the MongoDB Atlas website and create an account.

Follow these steps:

  1. Visit the MongoDB Atlas website.

  2. Sign up using your email address or an available authentication option.

  3. Verify your account if required.

  4. Sign in to the Atlas dashboard.

  5. Create a project for your application.

For example, you can name your project devbyte-project.

Creating a separate project helps you organize your database deployments and security settings.

Step 2: Create a MongoDB Cluster on AWS

After creating your project, you need to deploy a MongoDB database.

Follow these steps:

  1. Open your project in MongoDB Atlas.

  2. Navigate to the database deployment section.

  3. Select the option to create a database deployment.

  4. Choose AWS as your cloud provider.

  5. Select an AWS region close to your application server and users, where practical.

  6. Choose an available cluster tier that matches your requirements.

  7. Enter a cluster name, such as devbyte-cluster.

  8. Review the configuration and create the deployment.

Atlas will provision the database infrastructure.

Wait until the deployment is ready before attempting to connect.

Tip: For learning and development, start with an eligible low-cost or free option when available. For production, choose resources based on expected traffic, storage, and performance requirements.

Step 3: Configure MongoDB Database Access

Your application needs valid database credentials to connect to MongoDB.

In MongoDB Atlas, open the database access settings and create a database user.

For example:

  • Username: devbyte_user

  • Password: Use a strong, unique password.

  • Permissions: Grant only the database privileges your application requires.

Store the password securely.

Remember that your MongoDB Atlas account and your database user are different. Your Atlas account manages the cloud dashboard, while your database user authenticates connections to the database.

Avoid using an administrator account for everyday application operations.

Step 4: Configure Network Access

MongoDB Atlas restricts database connections based on its network access configuration.

To allow your computer or application server to connect:

  1. Open your project's network access settings.

  2. Select the option to add an IP address.

  3. Add your current public IP address for local development.

  4. Add a description, such as Development Mac.

  5. Save the entry.

Atlas will allow connections from the configured address, provided that the database credentials and other connection requirements are correct.

For production applications, configure access for the application server's approved network addresses or use private networking where appropriate.

Important security tip: Avoid allowing access from 0.0.0.0/0 unless you have a specific, carefully assessed reason. Restrict database access to trusted sources.

Step 5: Connect MongoDB Atlas Using MongoDB Compass

MongoDB Compass is a graphical interface that lets you explore databases, collections, and documents.

To connect your Atlas database:

  1. Open MongoDB Atlas.

  2. Select your database deployment.

  3. Click Connect.

  4. Choose the option to connect using MongoDB Compass.

  5. Copy the provided connection string.

  6. Open MongoDB Compass.

  7. Paste the connection string into the connection field.

  8. Replace the username and password placeholders with your database credentials.

  9. Click Connect.

Your connection string will look similar to this:

mongodb+srv://devbyte_user:<password>@devbyte-cluster.example.mongodb.net/

This is only an example. Use the actual connection string provided by Atlas.

If the connection succeeds, you can browse your databases and collections through MongoDB Compass.

If it fails, verify your network access list, credentials, connection string, and internet connectivity.

Step 6: Create a Database and Collection

Once connected, you can create a database for your application.

For example, create a database named devbyte_app and a collection named users.

You can insert a document using MongoDB Shell or the Compass interface.

Example MongoDB document:

{
  "name": "Manjeet",
  "email": "manjeet@example.com",
  "role": "developer",
  "createdAt": new Date()
}

MongoDB stores records as BSON documents, which support a flexible structure.

You can add fields to documents as your application's requirements evolve, while still maintaining appropriate validation and data modeling practices.

Step 7: Connect MongoDB Atlas to a Node.js Application

Now, let's connect your MongoDB database to a Node.js backend.

First, create a project and install the required packages:

mkdir mongodb-aws-demo
cd mongodb-aws-demo
npm init -y
npm install express mongoose dotenv

Create a .env file in the project root:

PORT=5000
MONGODB_URI=mongodb+srv://devbyte_user:<password>@devbyte-cluster.example.mongodb.net/devbyte_app

Replace the example connection string with your actual Atlas connection string. Use a properly encoded password if it contains special characters.

Next, create an index.js file:

require("dotenv").config();

const express = require("express");
const mongoose = require("mongoose");

const app = express();

app.use(express.json());

async function startServer() {
  try {
    await mongoose.connect(process.env.MONGODB_URI);

    console.log("MongoDB connected successfully");

    app.get("/", (req, res) => {
      res.json({
        message: "MongoDB Atlas connected successfully",
      });
    });

    app.listen(process.env.PORT || 5000, () => {
      console.log("Server is running");
    });
  } catch (error) {
    console.error("MongoDB connection failed:", error.message);
    process.exit(1);
  }
}

startServer();

Start your application:

node index.js

If the configuration is correct and the network permits the connection, your terminal should display a successful database connection message.

You can now build Express.js routes and Mongoose models for your application.

Security tip: Add .env to your .gitignore file. Never commit database passwords or connection strings containing credentials to GitHub. For production deployments, consider using a managed secrets service.

Step 8: Secure and Monitor Your Database

Before using MongoDB in production, review your database security and operational settings.

Follow these best practices:

  • Use strong database passwords and restrict user privileges.

  • Allow connections only from trusted IP addresses or private networks.

  • Use encrypted connections.

  • Configure suitable backup and recovery options.

  • Monitor database performance and resource usage.

  • Review database users and permissions regularly.

  • Store sensitive credentials securely.

  • Test database recovery procedures before you need them.

These practices help protect your database and improve the reliability of your application.

Common MongoDB Atlas Connection Errors

Here are some common issues developers encounter when connecting MongoDB to AWS-hosted infrastructure.

1. IP address not allowed: Add the correct client IP address to the Atlas network access list.

2. Authentication failed: Check the database username, password, and assigned permissions.

3. Server selection timeout: Check network connectivity, DNS resolution, firewall rules, and whether the database deployment is available.

4. Invalid connection string: Verify the connection string copied from Atlas and ensure special characters in the password are encoded correctly.

5. Application cannot connect: Confirm that the application server can reach Atlas and that its environment variables are configured correctly.

Troubleshooting these issues systematically can save time during development and deployment.

Conclusion

Setting up MongoDB on AWS using MongoDB Atlas is a straightforward way to create a cloud database for modern web applications.

In this tutorial, you learned how to create an Atlas account, deploy MongoDB on AWS infrastructure, configure database access, connect MongoDB Compass, create a database and collection, and integrate MongoDB with a Node.js application.

For production environments, focus on secure networking, appropriate database permissions, reliable backups, encrypted connections, and performance monitoring.

If you are developing a MERN stack application, MongoDB Atlas is a practical starting point for learning cloud database deployment without managing the database server yourself.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘