Preface
In actual development, there are many scenarios that require fuzzy querying. MongoDB shell fuzzy querying is very simple:
({'_id': /^5101/})
The above sentence is the content of query_id starting with '5101'.
Fuzzy query in old MogoDB is quite simple. Here is a simple record of the operation method of fuzzy query:
Under the command line:
db.letv_logs.find({"ctime":/uname?/i});
PHP operation
$query=array("name"=>new MongoRegex("/.*”.$name.".*/i")); $db->find($query);
The following mainly talks about how to query the new PHP driver:
$query = new \MongoDB\Driver\Query('_id' => ['$regex' => '^5101']); $this->getManager()->executeQuery($this->dbname . $this->collection, $query);
The above is a fuzzy query performed in the new driver. To be honest, I am quite complaining about this new driver. Compared with the old driver, this function name is too long. . . It's almost over the swift function name. Moreover, many functions on the old driver have been eliminated on the new driver. Although provided amongodb php library
The class library is used to operate, but this library has more than 60 files, sometimes more than my project files, so what's wrong with this? I suggest you encapsulate a Driver class to use this myself.
The above complaints are a bit off topic, except for direct fuzzy query, and$in
or$nin
When using it, you need to pay special attention:
$filter = ['_id' => ['$in' => ['$regex' => '^5101']]];
If you write filter like above, a fatal error will be thrown during execution:
PHP Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionException: $in needs an array in filename
Say here$in
An array needs to be provided, so let's put the above$filter
Change it and get an array for it:
$filter = ['_id' => ['$in' => [['$regex' => '^5101']]];
Unfortunately, I still couldn't get the desired result successfully:
PHP Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionException: cannot nest $ under $in in filename
Say here$in
$ cannot appear in the middle, so what should I do? Actually$in
or$nin
To use fuzzy matching, you need to use\MongoDB\BSON\Regex
Examples of class:
$filter = ['_id' => ['$in' => [new \MongoDB\BSON\Regex('^5101','i')]]];
This time we finally got the result we wanted.
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.