jM2.me jM2.me - 2 months ago 12
PHP Question

How to make "LIKE" query work in MONGODB using PHP?

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?

Answer

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));