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

时间:2016-01-10 16:09:28

标签: php regex mongodb php-mongodb

将MongoDB与PHP MongoDB driver一起使用我无法使用正则表达式过滤搜索结果。在手册中没有给出如何使用"过滤器"选项: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种不同的可能性,但无法找到答案。没有正则表达式的查询工作正常。

2 个答案:

答案 0 :(得分:5)

我很蠢。这样:

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

将找到所有带有" m"在该领域的某个地方" fieldname"。

答案 1 :(得分:2)

在从已弃用的mongo-driver转移到新的mongodb-driver之后,我遇到了同样的问题。到目前为止,接受的答案是好的。但是这些额外的信息也可能有所帮助:

旧驱动程序(请参阅php.net)需要完整的正则表达式,包括斜杠,如下所示:

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

新驱动程序需要删除斜杠。此外,有两种方法可以提交正则表达式,请参阅mongodb-driver-board

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

请注意,常见的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);
}