How to Connect MongoDB Atlas Cluster From an Application?
To connect your application to MongoDB Atlas, a cloud-based, fully-managed NoSQL database, you'll first need to set up a MongoDB Atlas cluster and configure a few essential settings. MongoDB Atlas offers a secure, scalable platform to manage your database without the hassle of manual maintenance, backups, or server management.
In this article, we will walk you through the steps to create a new MongoDB Atlas cluster, create a new user, whitelist your IP address, and retrieve the connection string to connect your application to the MongoDB Atlas cluster.
What is MongoDB Atlas?
MongoDB Atlas is a fully-managed, cloud-based version of MongoDB, a NoSQL database. It provides a secure, scalable platform for managing MongoDB databases without the need for manual server management, maintenance, or backups. Atlas offers features like automated scaling, high availability, built-in security, and backup options, all while running on major cloud providers such as AWS, Google Cloud, and Microsoft Azure.
Create a MongoDB Atlas Account and Cluster
To begin using MongoDB Atlas, you’ll need to create an account and set up your cluster. Follow these simple steps to get started:
Step 1: Create a New Account
- Visit the MongoDB Atlas website: Go to MongoDB Atlas and click on "Start Free" to begin the registration process.
- Sign up: You can sign up using your email address, Google account, or GitHub account.
- Complete registration: Follow the on-screen prompts to verify your email and complete the registration process.
Step 2: Creating New Cluster
- Log in to MongoDB Atlas: Once your account is set up, log in to your MongoDB Atlas dashboard.
- Create a new cluster: After logging in, you’ll be prompted to create your first cluster. You can choose the free M0 tier to start exploring MongoDB Atlas.
- Configure the cluster: Choose your cloud provider (AWS, Google Cloud, or Azure) and select a region that is geographically closer to your application's location to reduce latency. Name your cluster and click "Create Cluster."
Create a New Database User
After completing registration you will be redirected to the Quick Start page in a Security Section, where you have to create a new database user and Whitelisting your IP Address by which you can access your Database. You can also create a new Database user by following this:
Step 1: Navigate to Create a New User
To create a new user, In Sidebar you will find a Database Access page in a Security section. Open that page and click on ADD NEW DATABASE USER button on the top right hand side to create a new database user.
Step 2: Create a New User and Configure the Role
After that enter a Username and Password. Now, scroll down to Configure the privileges of that User. Scroll down to configure the user’s role. You can choose roles such as Read and Write or Read-Only based on your requirements. Once done, click on the Add User button to create a new user.
How to Whitelist Your IP Address
To allow your application to access the MongoDB Atlas database, it's essential to whitelist your IP address. This process essentially grants permission for specific devices or networks to connect to your database.
Step 1: Navigate to the Network Access Page
In the MongoDB Atlas dashboard, go to the Security section in the left-hand sidebar. Click on the Network Access option, which will take you to the page where you can manage your IP address whitelist settings.
Step 2: Whitelist and Configure IP Address
After that Click on ADD CURRENT IP ADDRESS button to add your current IP Address. It is recommended that you add a 0.0.0.0/0 IP Address by clicking on the ALLOW ACCESS FROM ANYWHERE button so you can access your cluster with any device with your username and password. You can also Add an IP Address for temporarily by enabling that option. After doing that click on the Confirm button to add the IP Address.
Retrieve the Connection String and Choose MongoDB Driver
To connect your Node.js application to MongoDB Atlas, you'll need to retrieve the connection string from the Atlas dashboard. The connection string is essential for establishing a connection between your application and the MongoDB cluster.
Step 1: Navigate to Connect Page
To obtain the connection string and select the appropriate driver, go to the Deployment section in the left-hand sidebar of the MongoDB Atlas dashboard. Click on the Database page under Deployment, and then click the Connect button at the top right. This will take you to the connection options page where you can configure the details for connecting your application to MongoDB Atlas.
Step 2: Choose Driver Option
After that it will show you all the options to access your data through tools and applications. Among those options choose the Drivers. After that select a driver according to your application requirement and follow the given step-by-step instruction to install driver and get a connection URL. It provides Drivers for languages such as Node.js, Java, C, C++, Python, Kotlin, .NET, etc.
Example: Connect MongoDB Cluster with Node.js
In this example, we will use the MongoDB Node.js driver to connect a Node.js application to a MongoDB Atlas cluster. Follow the steps below to set up your application, configure the connection, and interact with the cluster. This guide will help us perform essential operations such as connecting to the database, inserting data, and querying it seamlessly.
Step 1: Get the Connection URL from MongoDB Atlas
To get a Connection string follow the instructions given above, By choosing Node.js Driver the connection string will look like this:
mongodb+srv://<username>:<password>@cluster0.k018jn6.mongodb.net/?retryWrites=true&w=majority
Step 2: Create a new Project and Install Driver
To create a new project, first make sure that Node.js and NPM (It will be included in Node.js) is installed and paths are defined. Now create a new folder and then open the terminal and move to that folder. After doing this type the following command into your terminal:
npm init
After doing this, Install MongoDB Driver by using the following command:
npm install mongodb
Make sure you have properly completed the project setup.
Step 3: Create an index.js File
After project setup is completed, create an index.js file, this is the main file of our application. The below code will automatically create a new database and collection (if not present) and insert a new document (data) inside a collection then it is retrieves the document that we have inserted.
// Import the MongoDB Node.js driver
const { MongoClient } = require('mongodb');
// Replace uri with your actual connection string
//const uri = "mongodb+srv://<username>:<password>@cluster0.k018jn6.mongodb.net/?retryWrites=true&w=majority";
const uri = "YOUR_CONNECTION_URI";
const dbName = 'GeeksforGeeks';
// Function to connect to MongoDB Atlas and perform operations
async function connectToMongoDB() {
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
// Connect to MongoDB Atlas
await client.connect();
console.log('Succesfully Connected to MongoDB Atlas');
// Access the database
const database = client.db(dbName);
// Access a collection
const collection = database.collection('GeeksforGeeks');
// Insert a document
const document = { name: 'Jaimin', age: 20 };
const result = await collection.insertOne(document);
console.log(`Succesfully inserted document into the collection`);
// Query the collection
const query = { name: 'Jaimin' };
const foundDocument = await collection.findOne(query);
console.log('Found document:', foundDocument);
} finally {
// Close the MongoDB Atlas connection
await client.close();
console.log('Connection to MongoDB Atlas closed');
}
}
// Calling connectToMongoDB function
connectToMongoDB();
Step 4: Run Your Application
To run your application, run the following command in your project folder:
node index.js
Conclusion
In conclusion, this article provides a detailed step-by-step guide to connecting your application to MongoDB Atlas. From creating an account, setting up a new cluster, and creating a user to whitelisting your IP address and retrieving the connection string, you now have all the necessary knowledge to get started. Additionally, the example with Node.js demonstrates how to interact with MongoDB Atlas and perform basic database operations like inserting and retrieving documents.