Node.JS & MongoDB – Looping through Collection using core MongoDB library


As we all know that MongoDB is very good companion to Node.JS because of the linkage with JSON which is common to both the platforms. JSON is an integral part of Node.JS as it is JavaScript and MongoDB stores data in Binary JSON format.

Now the question is how to perform some simple operations like looping through the objects in collection. This article assumes that you have already installed the core MongoDB library using Node Package Manager (NPM).

sudo npm install mongodb

Now the very first step is to declare the variables pointing to the ‘MyDB’ database in MongoDB:

===================================================================================

// MongoDB Connection
var Db = require('mongodb').Db,
    Connection = require('mongodb').Connection,
    Server = require('mongodb').Server,
    BSON = require('mongodb').BSONNative;

var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;

var db = new Db('MyDB', new Server(host, port, {}), {native_parser:true});

===================================================================================

Now lets assume there is a collection called Customers in our MyDB database and we need to loop through it.

===================================================================================

db.open(function(err, db) {
    db.collection('Customers', function(err, collection) {
        collection.find(function(err, cursor) {
            cursor.each(function(err, customer) {
                if(customer != null){
                    console.log('First Name: ' + customer.firstName);
                    console.log('Last Name: ' + customer.lastName);
                }
                else{
                    db.close();
                }
            });
        });
    });
});

===================================================================================

Hope you will find this useful.

Till then Happy Coding!!!

Leave a comment