问题
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.
回答1:
I am stupid. This:
'fieldname' => array('$regex' => 'm')
will find all documents with an "m" somewhere in the field "fieldname".
回答2:
I was struggeling with the same problem, after moving from the deprecated mongo-driver to the new mongodb-driver. The accepted answer is good, so far. But this additional information may be helpful, too:
The old driver (see php.net) requires the complete regular expression, including slashes, like this:
$query1 = [ 'field' => new MongoRegex("/d+/i") ];
The new driver needs the slashes removed. Also, there are two ways to submit regular expressions, see mongodb-driver-board:
$query1 = [ 'field' => [ '$regex': => '\d+' ]];
$query2 = [ 'field' => new MongoDB\BSON\Regex('\d+'), 'i'];
Note that common reg-ex-flags are coming as the second parameter. Of course, you are free to leave, them. As I did in the first line. By the way, at the end, it looks like both ways are translated to the same:
{"field":{"$regex":"\d+","$options":"i"}}
If you want to keep it dynamic, because you don't know if it's a search string or a regular expression, here is a code example:
if(@preg_match($value, null) !== false){
$value = new MongoDB\BSON\Regex(trim($value, '/'), 'i');
// alternatively you may use this:
// $value = array('$regex' => trim($value, '/'));
// with options, it looks like this:
// $value = array('$regex' => trim($value, '/'), '$options' => );''
}
$search = array($field => $value);
$options = [
"skip" => 0,
"limit" => 10,
"projection" => NULL
];
$query = new MongoDB\Driver\Query($search, $options);
$cursor = $this->mongo->executeQuery($database.'.'.$collection, $query);
}
来源:https://stackoverflow.com/questions/34707657/set-filter-with-regex-in-query-with-phps-mongodb-driver-query-class