How to setup a database using MongoDB Atlas

MongoDB Atlas is a popular and widely used DBaaSdatabase-as-a-service platform created by the same developers that designed and maintain MongoDB. It is a handy tool for the development community as it can deploy and scale a database without users worrying about physical hardware, software updates, and configuration details.

How does MongoDB Atlas work

MongoDB Atlas is a cloud provider that automates the complexity of deploying and managing databases on any cloud provider of our choice (AWS, Azure, and GCP). It is the most efficient way to use MongoDB in the cloud.

Installation

Before setting up our database, we need to install Atlas CLI. We can use the commands given below to install Atlas CLI on our local machines:

  • The following command installs the prerequisite for Atlas:

    $ sudo apt-get install gnupg
    
  • The following command imports the public GPG key for MongoDB:

    $ wget -qO - https://pgp.mongodb.com/server-5.0.asc | sudo apt-key add -
    
  • The following command creates a list file for our version of ubuntu (18.04):

    $ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
    
  • This command updates the package database:

    $ sudo apt-get update
    
  • The following commands install the atlas CLI:

    $ sudo apt-get install -y mongodb-atlas
    
  • Enter the following command to verify the success of installation:

    $ atlas
    

Creating a new project

Go to your MongoDB Atlas account and create an organization (See illustration below).

While setting up, set access permission to “Project Owner” as shown below:

Creating API keys

The next step is to create our API keys for this project. We use these API keys to access our database using CLI commands. Go to the “Access Manager” and generate API keys as shown below:

This will generate our database’s public and private keys (see illustration below). Copy and save these keys for later use.

Configure API access

To allow access to our database, we need to go to Network Access, “ADD IP ADDRESS” and select “ALLOW ACCESS FROM ANYWHERE”. This will make our database accessible from all IP addresses.

Connecting to the database using CLI

We write the following command in the terminal below:

$ atlas config init

This will prompt us to enter the API keys we generated by following the steps above. Upon successfully entering the API keys, Atlas will configure our profile.

Enter the API keys we generated in the terminal below, and it will successfully configure the profile.

Terminal 1
Terminal
Loading...

Creating a cluster using sample data

Atlas has a straightforward method to create a sample cluster. It performs all the required steps to create a cluster and load sample data on a single command:

$ atlas quickstart --default --force 

Copyright ©2024 Educative, Inc. All rights reserved