Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb\BSON\Regex Php: Perform Like Match

Tags:

regex

php

mongodb

I see these links:

https://docs.mongodb.com/php-library/current/tutorial/crud/#regular-expressions https://docs.mongodb.com/manual/reference/operator/query/regex/#perform-a-like-match

On mongo terminal regex "/giov/i" Found:

  • Mariogiovanni
  • Giovanni

On php with

$cursor = $collection->find([
    'description' => new MongoDB\BSON\Regex(' /giov/', 'i'),

]);

nothing coming back. Why? I try some solution find on this community but nothing

like image 218
Sum_Pie Avatar asked Feb 12 '26 08:02

Sum_Pie


1 Answers

Remove the regex delimiters since they are not used in MongoDB\BSON\Regex:

$cursor = $collection->find([
    'description' => new MongoDB\BSON\Regex('giov', 'i'),

]);

The answer is quite evident if you follow your first reference link:

The following example lists documents in the zips collection where the city name starts with “garden” and the state is Texas:

<?php

$collection = (new MongoDB\Client)->test->zips;

$cursor = $collection->find([
    'city' => new MongoDB\BSON\Regex('^garden', 'i'),
    'state' => 'TX',
]);

foreach ($cursor as $document) {
   printf("%s: %s, %s\n", $document['_id'], $document['city'], $document['state']);
}
like image 187
Wiktor Stribiżew Avatar answered Feb 14 '26 20:02

Wiktor Stribiżew



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!