Free text search in MongoDb

30 / Jun / 2014 by Sakshi Tyagi 0 comments

MongoDb introduced free text search beta in its v2.4 but it was in experimental phase. In v.2.6, MongoDb has finally made its free text search (the most requested feature) production ready.

In this post, we will have a look at how can we use this pretty useful feature that MongoDb offers us.

To enable Free text search, Mongodb introduced ‘text’ indexes, for example if you want to enable free text search on ‘usernames` in User collection then you can do so using the statement below:

db.user.ensureIndex({ 'username': 'text' })

Now, we will need to use $text operator in the query to get the search results. Your query should look like below:

{"$text": {"$search" : , "$language": }}

By default, MongoDb performs the OR of search terms supplied in the $search field. You can also specify a language code in $language field, which defines the stop words and tokeniser used by MognoDB for the search. If the $language is not specified in the query, it will use the default language of the text index which is english by default unless specified while creating text index.

For eg. if we query our User collection with the following query:

db.user.find({"$text": {"$search": 'sakshi tyagi'}})

This query will return all the results in the User collection wherever the username field has either sakshi or ‘tyagi`. Also its very easy to exclude the records that include a search term. For example, you want to search for usernames containing `sakshi` but not `tyagi` then you can do so easily putting ‘-‘ sign before the term like below.

db.user.find({"$text": {"$search": 'sakshi -tyagi'}})

This is all for now, in next post we will dive in more details on how to define multiple indexes and solve more complex search use cases with MongoDB.
Hope this will help 🙂

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *