I want to search the result in MongoDB like in the following scenario.
I have data like Hello World, I am here.
My Query is:
{"$or": [{"data.title": {"$regex": search}}]}; //search = Hello
So i am searching it using $regex. but the problem is that if i type search = H, then again its returning the data
I want to search on the basis complete word only. (example: Hello or World) not on the basis of Characters (example: H or e)
Regular Expressions are frequently used in all languages to search for a pattern or word in any string. MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language.
MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support. For restrictions on particular syntax use, see $regex vs. /pattern/ Syntax. The following <options> are available for use with regular expression.
Create a Wildcard Index on All Fields With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array.
You can use the \b (word boundary) operator, eg:
{"$or": [{"data.title": {"$regex": /\bHello\b/i}}]}
In this way, searching for "/\bH\b/" won't match "Hello".
Otherwise, use a $text index on your title field, then do a $text search:
{"$or": [{$text:{$search:"Hello"}}]}
For more information about text search, look at the documentation: http://docs.mongodb.org/manual/administration/indexes-text/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With