Node.js Connect to MongoDB

Node.js Connect to MongoDB – In this Node.js Tutorial, we shall learn to connect to MongoDB from Node.js Application.


  1. Make sure MongoDB is installed. If not, install MongoDB.

Step by step guide

To connect to MongoDB from Node.js Application, following is a step by step guide.

  1. Start MongoDB service. Run the following command to start MongoDB Service
  2. Install mongodb package using npm (if not installed already).
  3. Prepare the url. A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell. While the Mongo Shell starts up, it echoes back the base url of MongoDB.
  4. With the help of mongodb package, create a MongoClient and connect to the url.

Example Program – Node.js Connect to MongoDB

Following is an Example Node.js program to make a Node.js MongoDB Connection.

Conclusion :

In this Node.js MongoDB – Node.js Connect to MongoDB, we have learnt to find the url of the MongoDB Service and connect to the service from Node.js using MongoClient’s connect method, demonstrated by an Example program.