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

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

name :'text',
review :'text'
weights :
name : 5,
review : 2


{ $text: { $search : searchString } },
{ score : { $meta: "textScore" }
{ 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.




Golang | Node.js

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Benefits of using Reactjs Development Frameworks

Ternary Operator in JavaScript: The Complete Guide

Quick Testing of RESTful services

Mariya Zeltsman_NFT Collaboration Drop_Pjt WITH UKRAINE

The thing about This

A little things of Javascript

Componet Export Route(CER)

React User Mgmt System with AWS Cognito

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store