Tabish
Tabish

Reputation: 1722

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)

Upvotes: 5

Views: 7774

Answers (1)

Stefano Castriotta
Stefano Castriotta

Reputation: 2913

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/

Upvotes: 10

Related Questions