Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make "LIKE" query work in MongoDB?

I have a list of street names and I want to select all that start with "Al". In my MySQL I would do something like

SELECT * FROM streets WHERE "street_name" LIKE "Al%"

How about MongoDB using PHP?

like image 734
jM2.me Avatar asked Apr 27 '11 00:04

jM2.me


2 Answers

Use a regular expression:

db.streets.find( { street_name : /^Al/i } );

or:

db.streets.find( { street_name : { $regex : '^Al', $options: 'i' } } );

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

Turning this into PHP:

$regex = new MongoRegex("/^Al/i");
$collection->find(array('street_name' => $regex));
like image 58
ceejayoz Avatar answered Oct 05 '22 01:10

ceejayoz


See: http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart

Also, highly recommend just using the native mongodb connector from PHP instead of a wrapper. It's way faster than any wrapper.

http://php.net/class.mongodb

like image 27
Homer6 Avatar answered Oct 05 '22 01:10

Homer6