Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB / PHP Library: $regex does not work

Tags:

regex

php

mongodb

There are no errors & also no results. My query looks like this:

Array
(
    [$or] => Array
        (
            [0] => Array
                (
                    [title] => Array
                        (
                            [$regex] => /.*Palmer \- The ArT oF.*/
                            [$options] => i
                        )

                )

        )

)

If I change title to match the entire string from database, it works.
I tried the same query with MongoChef and it works.

Also tried to change the title value with:
1. new MongoDB\BSON\Regex('Palmer - The ArT oF', 'i');
2. direct regex string /.*Palmer \- The ArT oF.*/i
...but still no results.

This is the Cursor object of the find() operation:

MongoDB\Driver\Cursor Object
(
    [cursor] => Array
        (
            [stamp] => 0
            [is_command] => 
            [sent] => 1
            [done] => 1
            [end_of_event] => 1
            [in_exhaust] => 
            [has_fields] => 
            [query] => stdClass Object
                (
                    [$query] => stdClass Object
                        (
                            [$or] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [title] => stdClass Object
                                                (
                                                    [$regex] => /.*Palmer \- The ArT oF.*/
                                                    [$options] => i
                                                )

                                        )

                                )

                        )

                )

            [fields] => stdClass Object
                (
                )

            [read_preference] => Array
                (
                    [mode] => 1
                    [tags] => Array
                        (
                        )

                )

            [flags] => 0
            [skip] => 0
            [limit] => 0
            [count] => 1
            [batch_size] => 0
            [ns] => laravel.movie_list
        )

    [server_id] => 1
)

I'm using the mongo-php-library for this operations.

like image 378
tbutcaru Avatar asked Feb 14 '26 02:02

tbutcaru


1 Answers

We should use '^Hello' instead of /^Hello/'. So, the following will work:

$filter = ['NAME' => new MongoDB\BSON\Regex('^Hello', 'i')]; // Works
$cursor = $collection->find($filter);

That's it.

like image 192
CEDA Avatar answered Feb 15 '26 19:02

CEDA