How To Connect MongoDB

Introduction

In this article, we will see how to connect MongoDB in detail. Many of us will make mistakes while connecting to the database. This article will help you to set up MongoDB properly and connect to your database.

Set up MongoDB

Step 1

Open https://account.mongodb.com/account/login

Step 2

Click on login with Google.

How to connect MongoDB

Step 3

Enter your Email ID and click on Submit.

How to connect MongoDB

Step 4

Change the "Organization", "Project Name" and select one language from "What is your preferred language?". Click on Continue.

How to connect MongoDB

Step 5

Click on "Shared Clusters". Click on "Create a cluster".

How to connect MongoDB

Step 6

Choose anyone from "Cloud Provider & Region". Select relevant "Religion" and click on "Create Cluster".

How to connect MongoDB

Step 7

This page will be ready now. Click on "CONNECT".

How to connect MongoDB

Step 8

Give "Username" and "Password" and then click on "Create Database User". This will be your <dbusername> and <dbpassword>.

How to connect MongoDB

Step 9

Don't make any changes. Click on "Add an IP address" and then click on "Choose a connection method".

How to connect MongoDB

Step 10

Now click on "Close".

How to connect MongoDB

Step 11

Click on "COLLECTIONS".

How to connect MongoDB

Step 12

Click on "Add My Own Data".

How to connect MongoDB

Step 13

Give the "DATABASE NAME" and "COLLECTION NAME" then click on "Create".

How to connect MongoDB

Step 14

Click on "INSERT DOCUMENT" and add some data like this,

How to connect MongoDB

How to connect MongoDB

Step 15

Click on "Insert".

Step 16

This will be your <dbanme> and <collectionname>.

How to connect MongoDB

What next?? Where to get Connection URL? How to add a connection URL?

Step 1

Go to Browser. Open https://cloud.mongodb.com/v2/60cb6fd983b16a16db9f8553#clusters

Step 2

Click on "CONNECT" and click on "Connect your application". 

Step 3

Copy the highlighted line and paste this line on the server.js file.

How to connect MongoDB

Step 4

Now update the dbusername, dbpassword, dbanme.

Step 5

Also, update this line,

collection = client.db("dbname").collection("collectionname"); 
// Provide your dbname and collectionname

Step 6

This is how your server.js file looks like,

How to connect MongoDB

Step 7

That's all. You are all set to run the application which connects backend MongoDB.

Conclusion

In this article, we have learned step-by-step procedures to set up MongoDB from the scratch. Also, we have seen how we can create a cluster, database, collection, and connect URL via server.js file which in turn communicates with MongoDB on the backend. Hope you find this article helpful. If you have any queries/concerns, please drop a comment. Happy to help. Thank you.


Similar Articles