1
_id:1
email:"j@g.com"

This is my collection. When I write

{ email: /^J/i  }

in compass it works absolutely fine, but in php

$user_collection->find(
    ["email" => ['$regex' => "/^j/i"]]
);

finds nothing

1 Answers1

0

In your example /^J/i, the i is an option flag to request case-insensitive search.

When using $regex you need to use a separate options field:

['$regex' => "^j", '$options'=>"i"]
Joe
  • 25,000
  • 3
  • 22
  • 44
  • 1
    `$user_collection->find( ["email" => ['$regex' => "^j", '$options'=>'i']] );` This is working for me. (excluding "/") – Tanmoon Taz Aug 02 '21 at 04:53
  • Thanks @TanmoonTaz, I had the same problem trying to use `/` in a MongoDb regex query `{ "values.QID24_TEXT": { $regex: /.*98763.*/, $options: "si" } }` (this throws an error in MongoDb Atlas). After I removed the `/` and placing quotes around the regex expression, the updated query `{ "values.QID24_TEXT": { $regex: ".*98763.*", $options: "si" } }` returned the expected document. – w. Patrick Gale Aug 06 '21 at 20:42