Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Mongo Regular expression

Tags:

regex

php

mongodb

I have mongo record as follows.

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

I want to search those records from mongo db having rec & rec2 element and having "data" element is in date format through Mongo regular expression. Is any way to find such records?

like image 496
Rahul Avatar asked Jun 18 '26 09:06

Rahul


2 Answers

From the shell you should be able to do something like the following:

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

From PHP, you would use the MongoRegex class.

Looks something like this:

$regex = new MongoRegex("/\d\d\d\d-\d\d-\d\d/");
$where = array("rec.data" => $regex);
$cursor = $db->foo->find( $where ); 
like image 59
Gates VP Avatar answered Jun 20 '26 00:06

Gates VP


Alternatively regular expressions can be expressed like so:

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

(i'm not sure if options can be omitted if it is blank so i've left it in)

like image 38
bigtallbill Avatar answered Jun 19 '26 22:06

bigtallbill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!