MongoDB Text Search

We can do a text based search in a MongoDB Collection based on text indexed fields.

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

In this tutorial, we will learn how to use perform text based search, with the help of examples.

Example – Text Search in MongoDB

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

ADVERTISEMENT

1. Text Fields in 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.

db.webpages.insert(
   [
     { _id: 1, title: "Java Tutorial", description: "Learn with Java Example Programs" },
     { _id: 2, title: "Node Tutorial", description: "Learn server side programming" },
     { _id: 3, title: "MongoDB Tutorial", description: "Welcome to MongoDB Database" },
     { _id: 4, title: "Python Tutorial", description: "Learn Python programming" },
     { _id: 5, title: "Kotlin Tutorial", description: "Learn Kotlin programming" }
   ]
)

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.

db.webpages.createIndex( { title: "text", description: "text" } )
> db.webpages.createIndex( { title: "text", description: "text" } )
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}

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.
> var searchItems = "database mongodb";

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

db.collection.find( { $text: { $search: searchItems } } )
> db.webpages.find( { $text: { $search: searchItems } } )
{ "_id" : 3, "title" : "MongoDB Tutorial", "description" : "Welcome to learn MongoDB Database" }

Conclusion

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