Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to match whole word in mongodb

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)

like image 318
Tabish Avatar asked Oct 04 '15 17:10

Tabish


People also ask

How do I search for a regular expression in MongoDB?

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.

Can we use regex in MongoDB?

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.

How do I use wildcard search in MongoDB?

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.


1 Answers

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/

like image 141
Stefano Castriotta Avatar answered Sep 21 '22 18:09

Stefano Castriotta