Detailed explanation of how php7 implements MongoDB fuzzy query
How to implement MongoDB fuzzy query in php7? I believe that the MongoDB fuzzy query statement is familiar to everyone. This article mainly introduces the method of implementing fuzzy query in MongoDB in PHP 7. The article gives a detailed introduction and sample code, which has certain reference and learning value for everyone. I hope to be helpful.
Preface
In actual development, there are many scenarios where fuzzy query needs to be used. MongoDB shell fuzzy query is very simple:
db.collection.find({'_id': /^5101/})
The above sentence is the content of query_id starting with '5101'.
Fuzzy query is quite simple in the old MogoDB. Here is a brief 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 in the new PHP driver:
$query = new \MongoDB\Driver\Query('_id' => ['$regex' => '^5101']); $this->getManager()->executeQuery($this->dbname . $this->collection, $query);
The above is the implementation of fuzzy query in the new driver. To be honest, I really complain about this new driver. Compared with the old driver, the function name is too long. . . It’s almost more than Swift’s function names. Moreover, many functions of the old driver have been removed from the new driver. Although a mongodb php library
class library is provided for operation, there are more than 60 files in this library, sometimes more than my project files. What's wrong with this. I recommend encapsulating a Driver class yourself for use.
The above complaint is a bit off topic. In addition to direct fuzzy query, when using it with $in
or $nin
, you need to pay special attention to:
$filter = ['_id' => ['$in' => ['$regex' => '^5101']]];
If you write the 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
It says that $in
needs to provide a Array, then we change the above $filter
and give it an array:
$filter = ['_id' => ['$in' => [['$regex' => '^5101']]];
But unfortunately, we still cannot successfully get the desired result:
PHP Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionException: cannot nest $ under $in in filename
It says $ cannot appear in $in
, so what should I do? In fact, to use fuzzy matching in $in
or $nin
, you need to use an instance of the \MongoDB\BSON\Regex
class:
$filter = ['_id' => ['$in' => [new \MongoDB\BSON\Regex('^5101','i')]]];
This time we finally got the results we wanted.
Related recommendations:
php implements Mongodb custom generation of self-increasing ID
The above is the detailed content of Detailed explanation of how php7 implements MongoDB fuzzy query. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
