Full-text search in MongoDB using Node.js and Mongoose

Albin Jose
2 min readJul 17, 2020

Most of the application built requires some sort of searching functionality. In most cases, searching is implemented using third-party applications like elasticsearch and solr. And the problem with these is you need to store data in multiple places, keep them synced. MongoDB’s Full-text search has provided a way to implement search to your application without the use of third-party applications. So if you only require full-text search then MongoDB’s full-text search will help you. There is no explicit support for partial or fuzzy matches, but stemming and stop words are supported. Partial text search to some extent can be done using regex.

We are using mongoose for accessing mongo. To work with mongo’s full-text search, first, we need to create indexes for the fields we need to search.

movieSchema.index({ name : 'text', review : 'text' })

In case there is an array with documents, 'arrayName.fieldname':'text' will work here.

movies.find({ $text : { $search : searchString }})

Providing weights to the index

movieSchema.index(
{
name :'text',
review :'text'
},
{
weights :
{
name : 5,
review : 2
}
}
)

Sorting

movies.find(
{ $text: { $search : searchString } },
{ score : { $meta: "textScore" }
}
).sort(
{ score: { $meta : 'textScore' } }
)

Wildcard Indexing

A wildcard index is used to index all the fields in a schema

movieSchema.index({ "$**" : "text" })

wildcard index can also be used to index a nested array

movieSchema.index({ "field.$**" : "text" })

MongoDB docs is a great resource. Check docs on Full-text search for more information.

--

--