Last active
January 6, 2017 19:44
-
-
Save julianYaman/0e29da602669d3678be87f538e6e1cd8 to your computer and use it in GitHub Desktop.
MongoRegex - Matching the exact word
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example: You have following documents with following content | |
// ['yourstring','yourstring1','1yourstring','23yourstring','your2string'] | |
// You only want the first document with the content "yourstring" | |
// but you don´t want to care about large and lowercase when somebody tries to find the document. | |
// Here is the solution: | |
// Connection to MongoDB | |
$m = new MongoClient(); | |
// Our search string | |
$search = "yourstring"; | |
// You can write your search string in large or lower case or in a mixed format. | |
// Connect to your collection | |
$db = $m->database; | |
$collection = $db->myCollection; | |
// MongoRegex | |
// Use "i" to search with case insensitive | |
// The '$' means that you only want the exact word you want to have | |
$regex = new MongoRegex("/^".$search ."\$/i"); | |
// Find the string | |
$query = $collection->find(array("strings" => $regex)); | |
// Counting the results | |
echo $query->count(); | |
// The output will be 1 because you only get "yourstring" as the final result. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment