Search code examples
phpregexmongodbphp-mongodb

Set filter with regex in query with PHP's MongoDB\Driver\Query class


Using MongoDB with PHP's MongoDB driver I am not able to filter search results with regular expressions. In the manual there are no examples given how to use the "filter" option: MongoDB\Driver\Query.

 $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
 $filter = array(?????);
 $options = array("projection" => array("fieldname" => 1));
 $query = new MongoDB\Driver\Query($filter, $options);
 $cursor = $manager->executeQuery("dbname.collectionname", $query);
 foreach($cursor as $document) {
    var_dump($document);
 }

I tried about 20 different possibilities but can't find the answer. Queries without regular expressions work fine.


Solution

  • I am stupid. This:

    'fieldname' => array('$regex' => 'm')
    

    will find all documents with an "m" somewhere in the field "fieldname".