MongoDB Text Search

To do MongoDB Text Search, MongoDB provides $text query operator. $text query operator works in conjunction with text indexed fields.


Following is a step by step guide to perform MongoDB Text Search in a MongoDB Collection.

  1. Have Text Fields in the Collection.

    Please make a note that text search can be done only on text indexed fields.
    For this example we shall use webpages collection. You may create it using the following command

  2. Create an Index.

    Text search queries can be done on fields that has string content or array of strings. Create an index with those fields on which you would like to perform the search.

    Note : Make sure not to add every necessary and unnecessary field to the index. Add only those that you deem to be necessary. Number of fields in the index affect the overhead on the collection to reindex when there is a modification to the Collection.

  3. Prepare search items.

    Multiple elements which needs to be searched could be included in the search items.
    Following table gives an idea of how to prepare search items.

    Search ItemsDescription
    “item_1 item_2 item_3”The three items are considered different and affect the text matching score individually and positively.
    “item_1 item_2 -item_3”Those field values that has item_3, would be excluded in the result.
    “item_1 /”item_2 tem_3/””“item_2 item_3” is considered a single item.
  4. Text Search.

    $text query operator is used to search the collection in the text indexed fields for the search items.
    Following is the command bringing everything needed together for $text query operation


Conclusion :

In this MongoDB Tutorial, we have learnt to do a text search in a MongoDB Collection with example.