PHP Mongo正则表达式

时间:2011-02-21 10:08:43

标签: php regex mongodb

我有mongo记录如下。

[1] => Array
    (
        [_id] => MongoId Object
            (
            )

        [id] => 195197
        [rec] => Array
            (
                [0] => Array
                    (
                        [id] => 195197
                        [data] => ways to skin a cat
                        [total] => 313
                    )

                 [1] => Array
                    (
                        [id] => 702724
                        [data] => 2010-07-25 15:09:40
                    )
            )

          [rec2] => Array
            (
                [0] => Array
                    (
                        [id] => 195197
                        [data] => ways to skin a cat
                        [total] => 313
                    )

                 [1] => Array
                    (
                        [id] => 702724
                        [data] => 2010-07-25 15:09:40
                    )
            )
    );

我想从具有rec& amp;的mongo db中搜索那些记录。 rec2元素和“data”元素是通过Mongo正则表达式的日期格式。有没有办法找到这样的记录?

2 个答案:

答案 0 :(得分:5)

从shell开始,您应该可以执行以下操作:

db.foo.find( { 'rec.data' : /\d\d\d\d-\d\d-\d\d/ } )

从PHP开始,您将使用MongoRegex class

看起来像这样:

$regex = new MongoRegex("/\d\d\d\d-\d\d-\d\d/");
$where = array("rec.data" => $regex);
$cursor = $db->foo->find( $where ); 

答案 1 :(得分:2)

或者正则表达式可以这样表达:

$where = array("rec.data"=>array('$regex'=>"\d\d\d\d-\d\d-\d\d", '$options'=>""));
$cursor = $db->foo->find( $where );

(我不确定如果选项是空白的话可以省略,所以我把它留在了)