7

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?

double-beep
  • 5,031
  • 17
  • 33
  • 41
jM2.me
  • 3,839
  • 12
  • 44
  • 58

7 Answers7

16

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));
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • Yes but how about in php? $database->streets->find(array("street" => "/^Al/i")); – jM2.me Apr 27 '11 at 00:52
  • As a side question, how does this compare in terms of raw speed? The thought of using regular expressions to filter a data set makes me cringe a little... Complete newbie at mongodb though. – Daniel Sloof Apr 27 '11 at 00:53
  • As long as the regex starts with ^ (i.e. match against the beginning of the string), indexes will be used. – ceejayoz Apr 27 '11 at 00:55
3

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

Homer6
  • 15,034
  • 11
  • 61
  • 81
2

here is my working example:

<?php
use MongoDB\BSON\Regex;
$collection = $yourMongoClient->yourDatabase->yourCollection;
$regex = new Regex($text, 's');
$where = ['your_field_for_search' => $regex];
$cursor = $collection->find($where);
//Lets iterate through collection
Ruslan Terekhov
  • 129
  • 1
  • 5
1

$collection.find({"name": /.*Al.*/})

or, similar,

$collection.find({"name": /Al/})

You're looking for something that contains "Al" somewhere (SQL's '%' operator is equivalent to regexps' '.*'), not something that has "Al" anchored to the beginning of the string.

koe
  • 736
  • 1
  • 12
  • 33
1

MongoRegex has been deprecated.
Use MongoDB\BSON\Regex

$regex = new MongoDB\BSON\Regex ( '^A1');
$cursor = $collection->find(array('street_name' => $regex));
//iterate through the cursor
Albert S
  • 2,552
  • 1
  • 22
  • 28
0
<?php
$mongoObj = new MongoClient();
$where = array("name" => new MongoRegex("^/AI/i"));
$mongoObj->dbName->collectionName->find($where);
?>

View for more details

Anil Singh
  • 11
  • 3
0

You can also do something like this

['key' => ['$regex' => '(?i)value']]
andranikasl
  • 1,242
  • 9
  • 10