Node.js MongoDB Tutorial

In this tutorial, we will learn how to interact with a MongoDB database using Node.js.

What is MongoDB?

MongoDB is a NoSQL database. MongoDB stores information in JSON format and it can support different kinds of data types.

MongoDB is schemaless, which means we don’t need to pre-define the structure of the data. In this tutorial, we will learn how to integrate MongoDB with Node.js.

MongoDB Installation

We need to install MongoDB in our system. I highly recommend you to check out the official installation page of MongoDB.

Once we have MongoDB installed, we can validate the installation by using the Mongo shell. Open the terminal and type mongo it should connect to the MongoDB daemon.

Node MongoDB tutorial

Node and NPM Installation

Check out our guide on Node installation on Ubuntu.

MongoDB basics

If you are new to MongoDB and it commands. Read this quick tutorial to get a heads up.

Creating our Node project

Open your terminal and create a new folder.

mkdir mongotest

Run this command to create a fresh Node project. It’s a good practice.

npm init --y

Let’s install the official MongoDB node module.

npm install --save mongodb

Connecting to MongoDB

Here is the code to connect to MongoDB using Node.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        console.log('database connected!');
        db.close();
});

Change the value of an URL if you are using MongoDB remote instance. All we did here is just fire up the connection and see if works. Here is a screenshot.

mongodb connection

Next, we need to select the database and create our collection in it.

Here is the code to do the same.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        console.log('database connected!');
        var dbo = db.db('codeforgeek');
        dbo.createCollection('users', (err, result) => {
            if(err) {
               console.log(err);
               process.exit(0);
            }
            console.log('collection created!');
            db.close();
        });
});

After a successful MongoDB connection, we select the MongoDB database.

        var dbo = db.db('codeforgeek');

Then, we try to create a collection naming users in the codeforgeek database.

Inserting data in the collection

Let’s add a few entries to our collection. Consider the code below.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
    if(err) {
       console.log(err);
       process.exit(0);
    }
    let data = [{
       "id": 100,
        "name": "Shahid"
    },{
        "id": 101,
        "name": "Rahil"
    },{
        "id": 102,
        "name": "John"
    }];
    var dbo = db.db('codeforgeek');
    console.log('database connected!');
    var collection = dbo.collection('users');
    collection.insertMany(data, (err, result) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        console.log(result);
        db.close();
    });
});

In the code shown above, we are using insertMany() function to add multiple entries at one go. However, you can also use insertOne() function to add single entries if you like.

This code should output something similar to this screenshot.

node mongodb tutorials

Find the data in collection

We can use find() function to search for the records in MongoDB.

Here is a code to show all the records present in the collection.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
    if(err) {
       console.log(err);
       process.exit(0);
    }
    var dbo = db.db('codeforgeek');
    console.log('database connected!');
    var collection = dbo.collection('users');
    collection.find().toArray((err, results) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        console.log(results);
        db.close();
    });
});

This code will retrieve all the records from the collection and print it on the terminal.

Node and MongoDB tutorial

You can also add search parameters to help you find specific documents. Just change the query to this:

    collection.find({name: 'shahid'}).toArray((err, results) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        console.log(results);
        db.close();
    });

Update the document in the collection

You can update the existing document using updateOne() function. The first parameter is for searching the document and the second is for updating it with new values. Here is the snippet.

collection.updateOne({name: 'Shahid'}, {'$set': {'name': 'Shahid Shaikh'}}, (err, results) => {
    if(err) {
        console.log(err);
        process.exit(0);
    }
    console.log(results);
    db.close();
});

Delete the document in the collection

You can delete the existing documents in the collection using deleteOne() function.

collection.deleteOne({name: 'Shahid'}, (err, results) => {
    if(err) {
        console.log(err);
        process.exit(0);
    }
    console.log(results);
    db.close();
});

Summary

As of now, we studied how to interact with MongoDB using Node.js. We can take a step forward and build something awesome such as an online book store, REST API, etc.

Further Study

Build a RESTful API using Node and MongoDB
Server Side Pagination Using Node and Mongo

Pankaj Kumar
Pankaj Kumar
Articles: 207