Install MongoDB

To start MongoDB integration with NodeJS, we have to download MongoDB Drivers using npm and then establish connection.

We will start with installing MongoDB drivers in NodeJS , followed by some CRUD Operations.

Make sure MongoDB server is running.

Install MongoDB Driver in NodeJS

npm i mongodb

This will install MongoDB driver and also add dependency in package.json file.


Configure MongoDB with NodeJS

After installing MongoDB drivers in NodeJS, we have to configure MongoDB in NodeJS. Make sure MongoDB server is running. If not, type mongod in terminal. Once the mongod process is started, we can configure MongoDB.

    /*mdb.js*/
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

    // Connection URL
const url = 'mongodb://localhost:27017';

    // Enter Database Name
const dbName = 'mydata';

    // Create a new MongoClient
const client = new MongoClient(url,{ useUnifiedTopology: true });

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);
  client.close();
});

Test Database Connection

To test database connection in NodeJS, run the filemdb.js from terminal.

Connected successfully to server

npm i mdb.js

Insert

To insert data in MongoDB through NodeJS, add code below. we are using MongoDB insertMany method to insert data. We can also use insert and insertOne methods.

        /*app.js*/
    
const insertDocuments = function(db, callback) {
        // Get the documents collection
    const collection = db.collection('documents');
 
        // Insert some documents
    collection.insertMany([
        {x : 1}, {y : 2}, {z : 3}
    ], function(err, result) {
        assert.equal(err, null);
        assert.equal(3, result.result.n);
        assert.equal(3, result.ops.length);
        console.log("Inserted 3 documents in collection");
        callback(result);
  });
}    
    

Insert Command in NodeJS

        /*app.js*/
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');


// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';
const client = new MongoClient(url, {useNewUrlParser: true, useUnifiedTopology: true});

const insertDocuments = function(db, callback) {
        // Get the documents collection
    const collection = db.collection('documents');
 
        // Insert some documents
    collection.insertMany([
        {name : "avi"}, {id : 212}, {pin : 123456}
    ], function(err, result) {
        assert.equal(err, null);
        assert.equal(3, result.result.n);
        assert.equal(3, result.ops.length);
        console.log("Inserted 3 documents in collection");
        callback(result);
  });
}

// Use connect method to connect to the server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  insertDocuments(db, function() {
    client.close();
  });
});
Connected successfully to server
Inserted 3 documents in collection        
node src/app.js

Find all documents

How to find all documents in MongoDB in NodeJS. we are using MongoDB Find Method.

Find all data in collection


const findDocuments = function(db, callback) {
   
    // Get the documents collection
    const collection = db.collection('documents');
   
     // Find some documents
    collection.find({}).toArray(function(err, docs) {
        assert.equal(err, null);
        console.log("Found the following records");
        console.log(docs)
        callback(docs);
    });
}

Find a query in collection

In the example below, we will find a query with key and value given.


const findDocuments = function(db, callback) {
   
    // Get the documents collection
    const collection = db.collection('documents');
   
     // Find some documents
    collection.find({type:'hatchback'}).toArray(function(err, docs) {
        assert.equal(err, null);
        console.log("Found the following records");
        console.log(docs)
        callback(docs);
    });
}

Update data in document


const updateDocument = function(db, callback) {
 
    // Get the documents collection
    const collection = db.collection('documents');
  
    // Update document where x is 5, set y equal to 8
    collection.updateOne({ x : 5 }
    , { $set: { y : 8 } }, function(err, result) {
    assert.equal(err, null);
    assert.equal(1, result.result.n);
    console.log("Updated the document");
    callback(result);
  });  
}    

Remove data in document


const removeDocument = function(db, callback) {
 
    // Get the documents collection
    const collection = db.collection('documents');
 
    // Delete document where name is swift
    collection.deleteOne({ name : 'swift' }, function(err, result) {
    assert.equal(err, null);
    assert.equal(1, result.result.n);
    console.log("Removed the document");
    callback(result);
  });    
}