How PHP uses regular expressions to query in MongoDB
Introduction:
MongoDB is a commonly used NoSQL database with a flexible data model and efficient query performance. Regular expressions are a very useful query technique when using MongoDB for data query. This article will introduce how to use PHP and MongoDB to perform regular expression queries.
pecl install mongodb
<?php $mongoClient = new MongoDBClient("mongodb://localhost:27017"); $mongodb = $mongoClient->selectDatabase("mydb"); $collection = $mongodb->selectCollection("mycollection"); ?>
In In the code, mongodb://localhost:27017
is the connection address of the MongoDB database, and the default port is 27017. mydb
is the name of the database, mycollection
is the name of the collection.
MongoDBBSONRegex
class to build a regular expression and then use it in the query. <?php $filter = ['name' => new MongoDBBSONRegex('^John', 'i')]; $options = ['sort' => ['name' => 1]]; $result = $collection->find($filter, $options); foreach ($result as $document) { echo $document->name . " "; } ?>
In the above code, we use the regular expression ^John
to query documents whose names start with John. In the process of constructing a regular expression, '^John'
is the pattern of the regular expression, and 'i'
is a modifier, used to indicate case insensitivity.
.*
to represent a wildcard of any character and combine it with modifiers to achieve more precise queries. <?php $filter = ['name' => new MongoDBBSONRegex('.*doe.*', 'i')]; $options = ['sort' => ['name' => 1]]; $result = $collection->find($filter, $options); foreach ($result as $document) { echo $document->name . " "; } ?>
In the above code, we use the regular expression .*doe.*
to query documents whose names contain the string "doe".
I hope this article will help you understand MongoDB's regular expression query in PHP!
The above is the detailed content of How to query using regular expressions in MongoDB using PHP. For more information, please follow other related articles on the PHP Chinese website!