在 PHP 的 MongoDB\Driver\Query class 查询中使用正则表达式设置过滤器

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

将 MongoDB 与 PHP 的 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);
 }

我尝试了大约 20 种不同的可能性,但找不到答案。没有正则表达式的查询工作正常。

我很笨。这个:

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

将找到字段 "fieldname".

中某处带有 "m" 的所有文档

从已弃用的 mongo-driver 迁移到新的 mongodb-driver 后,我遇到了同样的问题。到目前为止,公认的答案是好的。但这些附加信息也可能有帮助:

旧的driver(见php.net)需要完整的正则表达式,包括斜线,像这样:

$query1 = [ 'field' => new MongoRegex("/d+/i") ];

new driver 需要删除斜杠。另外,有两种提交正则表达式的方式,见mongodb-driver-board:

$query1 = [ 'field' => [ '$regex': => '\d+' ]];
$query2 = [ 'field' => new MongoDB\BSON\Regex('\d+'), 'i'];

请注意,common reg-ex-flags 将作为第二个参数出现。当然,你可以自由离开,他们。就像我在第一行所做的那样。顺便说一句,最后,看起来两种方式都翻译成相同的:

{"field":{"$regex":"\d+","$options":"i"}}

如果你想保持动态,因为你不知道它是一个搜索字符串还是一个正则表达式,下面是一个代码示例:

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