If we want SQL like “Like” operator in Mongo DB for string matching. But in mongo DB there is no such “like” operator instead it has regular expression to achieve a similar feature.
db.users.insert({name: 'singh'}) db.users.insert({name: 'singhak'}) db.users.insert({name: 'aksingh'})
Table of Contents
Case 1:
In MongoDB, you can also use regular expression objects (i.e. /pattern/
) to specify regular expressions:
Syntax: { <field>: /pattern/<options> }
Example 1.
--SQL SELECT * FROM users WHERE name LIKE '%sin%' --MongoDB db.users.find({name: /sin/})
Example 2.
--SQL SELECT * FROM users WHERE name LIKE '%gh' --MongoDB db.users.find({name: /gh$/})
Example 3.
--SQL SELECT * FROM users WHERE name LIKE 'ak%' --MongoDB db.users.find({name: /^ak/})
If we want ignorecase we can use like this
db.users.find({name: /Sin/i})
Also Read : Start mongo DB as Service
Case 2.
we can use $regex
operator, it provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. “PCRE” ) version 8.42 with UTF-8 support.
Examples
db.user.find( { name: { $regex: /ak$/ } } )
db.user.find( { name: { $regex: /^sin/ } } )
db.user.find( { name: { $regex: /Sin/i } } )
db.user.find( { name: { $regex: '.*IN.*', $options:'is' } } )
db.user.find( { name: { $regex: /^sin/ } } )
Reference : MongoDB Regex