December 20, 2016

How to print specific data from Collection or document using Javascript in MongoDB

How to print specific data from Collection or document using Javascript in MongoDB

Mongo supports javascript queries to handle the data and process as per the need.

For example,

Employee collection
 {  
   "_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"       
 },  
 {  
   "_id" : 3,  
   "name" : {  
     "first" : "Dhruv",  
     "last" : "Sharma"  
   },  
   "department" : "finance",  
   "joineddate" : "2010-09-07"       
 }  

Now, lets say I need to print only the name who are in finance department.

 db.employee.find("department" : "finance").forEach(     
   function(doc) {   
    print(doc.name.first + " " + doc.name.last);   
   );  

The above query will print all the employee first name and last name whose department is finance.
  

No comments:

Post a Comment