January 15, 2017

How to use like keyword in mongodb

Like SQL statements we can use LIKE keywords in Mongo as well. We can query mongdb with LIKE search. We can restrict LIKE search as we do in SQL using '%' as

db.employee.find({name: /text/})  //like '%text%'
db.employee.find({name: /^txt/})  //like 'text%'
db.employee.find({name: /text$/})  //like 'text%'
Examples:

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"      
  }   

Lets say from above collection I need to search for name which has 'h' in it. So, the query would be:

  db.employee.find({"name" : "/h/"},{name:1})  

The above will fetch 2 results from collection as:
  {    
   "_id" : 1,    
   "name" : {    
   "first" : "Abhi",    
   "last" : "Dev"    
   }  
  },  
  {    
   "_id" : 3,    
   "name" : {    
   "first" : "Dhruv",    
   "last" : "Sharma"    
   }   
  }  

Now, lets say I need to search name that start with 'A', so the query would be:
  db.employee.find({"name" : "/^A/"},{name:1})  

Query Output:
  {    
   "_id" : 1,    
   "name" : {    
   "first" : "Abhi",    
   "last" : "Dev"    
   }   
  },  
  {    
   "_id" : 2,    
   "name" : {    
   "first" : "Alok",    
   "last" : "Agrawal"    
   }   
  }   

There are many regex we can use similarly to filter the search as per the need.

No comments:

Post a Comment