So how to create a hello world program in mongoDB and mongodb node.js drivers. What the heck is node.js drivers? Actually the driver here stand for library, library in specific language for communicating with server. Here it is V8 Javascript language. It handle opening sockets, closing db, handling connections and so on. When we run ./mongod then mongod server listens for incoming connections and it actually aspects protocol called BSON (Binary JSON) protocol.
Look into this program :

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

// Open the connection to the server
MongoClient.connect('mongodb://localhost:27017/demo', function (err, db) {
    if (err) throw err;

    // Find one document
    db.collection('things').findOne({}, function (err, doc) {
        if (err) throw err;

        //Print the result
        console.dir(doc);

        // Close db
        db.close();
    });
    // Declare Success 
    console.dir("CAlled FindOne");
});

Explanation :

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

We created a variable MongoClient and in require(‘mongodb’) we tell that we need mongodb module.

MongoClient.connect('mongodb://localhost:27017/demo', function (err, db)

It open the connection to the server. MognoClient variable is use to connect with mongodb. By default mongodb is connected to 27014 port so we defined “mongodb://localhost:27017” and /demo is the name of database. We also created callback function here “function(err, db)” in which first parameter is dealing with error handling and second parameter dealing with database.

db.collection('things').findOne({}, function (err, doc)

This line is somewhat like main part of this program. In this we use db parameter and calling collection name “db.collections(‘things’)”. Here things is the collection name which we create in our database. FindOne() which is used to return one document that satisfies the specified query criteria. And within it we use to call {} which return first value and also we added call-back function in it.

 if (err) throw err;

This line will throw the error message if any error encounters.

//Print the result
  console.dir(doc);

console.dir prints the element in a JSON-like tree

// Close db
   db.close();

This will close database when all operations completed.

// Declare Success 
   console.dir("CAlled FindOne")

As we know mongodb is Synchronous in nature. So program first goes to this statement if no error encounters then it will print this first then rest of the program will execute.

To run program open terminal and type :
$ nodejs <fileName.js>
Advertisements