The MongoRegex class
(PECL mongo >=0.8.1)
Introduction
This class can be used to create regular expressions. Typically, these expressions will be used to query the database and find matching strings. More unusually, they can be saved to the database and retrieved.
Regular expressions consist of four parts. First a / as starting delimiter, then then pattern, another / and finally a string containing flags.
Example #1 Regular expression pattern
/pattern/flags
MongoDB recognizes six regular expression flags:
-
i: Case insensitive
-
m: Multiline
-
x: Can contain comments
-
l: locale
-
s: dotall, "." matches everything, including newlines
-
u: match unicode
Class synopsis
Table of Contents
- MongoRegex::__construct — Creates a new regular expression
- MongoRegex::__toString — A string representation of this regular expression
Коментарии
First you must declare and define your regexObj
Here I am looking for all entry of my database wich is like "%Nicolas%" and the /i param is used for Insensitive Case
$regexObj = new MongoRegex("/^Nicolas/i");
<?php
// I attach the regexObj to my Where Condition
$where = array("ctname" => $regexObj);
// Execute the request
$resultset = $this->db->Infos->find($where);
// Parsing the results
while ($resultset->hasNext())
{
$clientObj = $resultset->getNext();
echo "Client Name: ".$clientObj["cname"]."</br>";
}
?>
/*
Use the "i" option to make searches with Case Insensitive
Find results beginning with $q
*/
$search = "V";
// Case Sensitive
$where = array('name' => array('$regex' => new MongoRegex("/^$search/")));
$cursor = $collection->find($where);
//Case Insensitive
$where = array('name' => array('$regex' => new MongoRegex("/^$search/i")));
$cursor = $collection->find($where);
here is an example for case insensitive search.If there are two fields (user_name/company_name) in collection;
<?php
$search_string='baR';
$searchQuery = array(
'$or' => array(
array(
'user_name' => new MongoRegex("/^$search_string/i"),
),
array(
'company_name' => new MongoRegex("/^$search_string/i"),
),
)
);
$cursor = $customers->find($searchQuery);
?>