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 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 service is running, we can configure MongoDB.

For Mongodb 6 and 7

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

  // Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
  
  // Database Name
const dbName = 'node';
  
async function main() {
    // Use connect method to connect to the server
    await client.connect();
    console.log('Connected successfully to server');

    const db = client.db(dbName);
    const collection = db.collection('suzuki');
  
    // the following code examples can be pasted here...
  
    return 'done.';
}
  
main().then(console.log).catch(console.error).finally(() => client.close()); 

Mongodb 5 and below

    /*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((err)=>{
  assert.strict(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

node src/mdb

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.

For Mongo DB 6 and 7

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

  // Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
  
  // Database Name
const dbName = 'node';
  
async function main() {
    // Use connect method to connect to the server
    await client.connect();
    console.log('Connected successfully to server');

    const db = client.db(dbName);
    const collection = db.collection('suzuki');
  
    // insert in DB
    const insertResult = await collection.insertMany([{ name:"swift", type:"hatchback" },{ name:"grand vitara", type:"suv" }]);
    console.log('Inserted documents =>', insertResult); 

  
    return 'done.';
}
  
main().then(console.log).catch(console.error).finally(() => client.close()); 


For Mongo DB 5 and below

        /*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}
    ], (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}
    ], (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((err)=>{
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  insertDocuments(db, ()=> {
    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 in MongoDB 6 and 7

        /*app.js*/    
  const { MongoClient } = require('mongodb');
            
          // Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
              
          // Database Name
const dbName = 'node';
              
async function main() {
        // Use connect method to connect to the server
    await client.connect();
    console.log('Connected successfully to server');
            
    const db = client.db(dbName);
    const collection = db.collection('suzuki');
              
      // find in DB
    const findResult = await collection.find({type:"hatchback"}).toArray();
    console.log('Found documents =>', findResult);
            
              
    return 'done.';
}
              
main().then(console.log).catch(console.error).finally(() => client.close()); 
            
            

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((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((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 } }, (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' }, (err, result)=>{
    assert.equal(err, null);
    assert.equal(1, result.result.n);
    console.log("Removed the document");
    callback(result);
  });    
}