January 15, 2017

How to increase performance while fetching the data from MongoDB

MongoDB is a no-sql database, which can contain huge data in collections. Due to non relational /un-structered data, it takes load of time while fetching it from DB.

We can if query mongo smartly it can fetch the data very fastly. One way to do it is to limit the output data. There would be many cases when the objective of querying the mongo is to just get some specific fields details. For example, I have a collection of employee and I need to search employee first name starts from 'A' and I only need to fetch its first name. now one way is to use below query to fetch the data which will fetch the whole document which mets the criteria:

  db.employee.find({"name" : "/^A/"})  
Output:
{   
   "_id" : 1,   
   "name" : {   
    "first" : "Abhi",   
    "last" : "Dev"   
   },   
   "department" : "finance",   
   "joineddate" : "2000-04-10"      
  },   
  {   
   "_id" : 2,   
   "name" : {   
    "first" : "Alok",   
    "last" : "Agrawal"   
   },   
   "department" : "information",   
   "joineddate" : "2006-07-07"      
  }

But if I limit the data outcome and only specify the fields which I want as in this case I only need to see first name, we can use projection and make it possible as:
  db.employee.find({"name" : "/^A/"},{"name.first":1})  
Output
  {   
   "_id" : 1,   
   "name" : {   
    "first" : "Abhi"
   }   
  },   
  {   
   "_id" : 2,   
   "name" : {   
    "first" : "Alok   
   }      
  }

As we can see on above output it reduces the data, which will enhance the performance of query.

No comments:

Post a Comment