In php7, how does MongoDB implement fuzzy search? php7mongodb
Preface
In actual development, fuzzy queries are required in many scenarios. MongoDB shell fuzzy queries are simple:
db.collection.find({'_id': /^5101/})
The above sentence is the content starting with '123' for the query _ id.
In the old MogoDB, fuzzy query is quite simple. Here we will simply record the operation method of fuzzy query:
Command line:
db.letv_logs.find({"ctime":/uname?/i});
Php operations
$query=array("name"=>new MongoRegex("/.*”.$name.".*/i"));$db->find($query);
The following describes 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 the execution of fuzzy query in the new driver. To tell the truth, it's a bit of a new driver. This function name is too long compared to the old driver... The swift function name is almost exceeded. In addition, many functions of the old driver are eliminated on the new driver. Althoughmongodb php library
But the library contains more than 60 files, sometimes more than my project files. We recommend that you encapsulate a Driver class.
In addition to fuzzy queries$in
Or$nin
Pay special attention to the following:
$filter = ['_id' => ['$in' => ['$regex' => '^5101']]];
If you write a filter as above, a fatal error will be thrown during execution:
PHP Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionException: $in needs an array in filename
Here$in
We need to provide an array.$filter
Next, give it an array:
$filter = ['_id' => ['$in' => [['$regex' => '^5101']]];
However, unfortunately, you still cannot get the desired result successfully:
PHP Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionException: cannot nest $ under $in in filename
Here$in
$ Cannot appear in. What should I do? In fact$in
Or$nin
To use fuzzy match, use\MongoDB\BSON\Regex
Class instance:
$filter = ['_id' => ['$in' => [new \MongoDB\BSON\Regex('^5101','i')]]];
This time we finally got the desired result.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.