How to Access MongoDB Using Node.js

This tutorial will teach you how to access the document-based database MongoDB using Node.js.

To begin with, we need to install MongoDB drivers. You can use NPM to install native MongoDB drivers. Then, write the following command to install the MongoDB driver in your application.

npm install mongodb --save

This will include mongodb folder inside the node_modules folder. Now, let's start the MongoDB server with the following command.

mongod -dbpath C:\MyNodeJSConsoleApp\MyMongoDB 

1. How to Connect MongoDB

The following sample code(app.js) illustrates how to connect to the local MongoDB database.

var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
   
     if(err) throw err;

     //Write databse Insert/Update/Query code here..
                
});

2. How to Insert Documents

Use the following example to insert documents into MongoDB database.

var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
    
    db.collection('Persons', function (err, collection) {
        
        collection.insert({ id: 1, firstName: 'Steve', lastName: 'Jobs' });
        collection.insert({ id: 2, firstName: 'Bill', lastName: 'Gates' });
        collection.insert({ id: 3, firstName: 'James', lastName: 'Bond' });
        
        

        db.collection('Persons').count(function (err, count) {
            if (err) throw err;
            
            console.log('Total Rows: ' + count);
        });
    });
                
});

3. How to Update Documents

You can use the sample below to update or delete an existing document.

var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
    
    db.collection('Persons', function (err, collection) {
        
        collection.update({id: 1}, { $set: { firstName: 'James', lastName: 'Gosling'} }, {w:1},
                                                     function(err, result){
                                                                if(err) throw err;    
                                                                console.log('Document Updated Successfully');
                                                        });

        collection.remove({id:2}, {w:1}, function(err, result) {
        
            if(err) throw err;    
        
            console.log('Document Removed Successfully');
        });

    });
                
});

4. How to Execute Query in the Database

The following example demonstrates how to execute a query in the MongoDB database.

var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
    
    db.collection('Persons', function (err, collection) {
        
         collection.find().toArray(function(err, items) {
            if(err) throw err;    
            console.log(items);            
        });
        
    });
                
});

From the above, you can connect and access the MongoDB database.



Leave a reply



Submit