DEV Community

Spurgeon Gnan Prakasham Tara
Spurgeon Gnan Prakasham Tara

Posted on

How to do a Text Search in MongoDB

A text index is created quite similar to how we create a regular index, except that it specifies the text keyword instead of specifying an ascending/descending order.

Indexing a Single Field
Create a text index on the subject field of our document using the following query:

1
db.messages.createIndex({"subject":"text"})
To test this newly created text index on the subject field, we will search documents using the $text operator. We will be looking for all the documents that have the keyword dogs in their subject field.

Since we are running a text search, we are also interested in getting some statistics about how relevant the resultant documents are. For this purpose, we will use the { $meta: "textScore" } expression, which provides information on the processing of the $text operator. We will also sort the documents by their textScore using the sort command. A higher textScore indicates a more relevant match.

Top comments (0)