How to query MongoDB with “like” ?
How to query MongoDB with “like” ?
This could be a best answer, Try by using below code:
db.users.find({"name": /.*m.*/})
or, related:
db.users.find({"name": /m/})
We are expecting for something that contains “m” somewhere (SQL’s ‘%‘ operator is equivalent to Regexp’s ‘.*‘), not something that has “m” anchored to the beginning of the string.
This is the alternative solution for the issue :
db.users.insert({name: 'paulo'}) db.users.insert({name: 'patric'}) db.users.insert({name: 'pedro'}) db.users.find({name: /a/}) //like '%a%'
output: paulo, patric
db.users.find({name: /^pa/}) //like 'pa%'
output: paulo, patric
db.users.find({name: /ro$/}) //like '%ro'
output: pedro
The following code can be used in PHP:
$collection->find(array('name'=> array('$regex' => 'm'));