How to connect MongoDB?

Pranam Bhat
3 min readJun 30, 2021

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:

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

2. Click on Log in with Google

3. Enter your Email ID and click on Submit.

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

5. Click on “Shared Clusters”. Click on “Create a cluster”.

6. Choose any one from “Cloud Provider & Region”. Select relevant “Religion” and click on “Create Cluster”.

7. This page will be ready now. Click on “CONNECT”.

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

9. Don’t make any changes. Click on “Add an IP address” and then click on “Choose a connection method”.

10. Now click on “Close”.

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

Click on “COLLECTIONS”.

12. Click on “Add My Own Data”.

13. Give the “DATABASE NAME” and “COLLECTION NAME” then click on “Create”.

14. Click on “INSERT DOCUMENT” and add some data like this:

15. Click on “Insert”.

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

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

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

2. Click on “CONNECT” and click on “Connect your application”.

3. Copy the highlightedd line and paste this line on server.js file.

4. Now update the dbusername, dbpassword, dbanme.

5. Also update this line:

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

6. This is how your server.js file looks like:

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

Conlcusion:

In this article we have learned step by step procedure to set up the MongoDB from the scratch. Also, we have seen how we can create a cluster, database, collection and to 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 query/concerns, please drop a comment. Happy to help. Thank you.

--

--