How To Connect Mongo Db in Node js

Posted By : Rajat khurana | 26-Sep-2017

Hi Guys,

Here you will learn MongoDb and its connection in node js. As you know, MongoDB is open-source document based database and it provides very high performance , high availability and easy scalability. MongoDB is written in C++ language.

1. Data Storage in Mongo db 
MongoDB stores data in  JSON-like format, meaning fields can vary from document to document eg.
{
     "_id" : ObjectId("59c745ff31e3f713705657b4"),
    "name" : "k333",
    "updated" : ISODate("2017-09-24T05:43:27.423Z"),
    "__v" : 0
}

_id is a 12 bytes hexadecimal number which tell the uniqueness of each and every document. You can give unique _id during insertion of document. If id is not provided by you then MongoDb create a unique id for every document during insertion . Id contain 12 bytes out of which  first 4 bytes are for the current timestamp, next 3 bytes are for machine id, next 2 bytes contain  process id of MongoDB server and remaining 3 bytes are simple incremental value.

2. To set connection with Mongodb in node js, we need to install its module from npm registry using command:-

a). npm install mongo

b). Created a file and mention below code to connect to mongo db.

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..

});

 where MyDb is database name. You can check database is created or not by run these command:

3. To get inside of mongo run "mongo" from terminal to start mongo Db. Different command used in mongo Db

a) show dbs; where all database are listed.
b) show collections, where all collections( tuples in mysql) are listed
c) db.collectionname.find().pretty() , will display list of documents ( row in mysql) in json format.

For more commands go through Mongo Db documentation.

Thanks 

About Author

Author Image
Rajat khurana

Rajat is a bright Javascript Developer, he has good knowledge of HTML, WordPress, NodeJs, Core Java, Javascript, Jquery. Apart from this he loves to play Badminton and PC Gaming.

Request for Proposal

Name is required

Comment is required

Sending message..