How to implement a search feature in a mongo db database

Govinda Prakash
1 min readApr 9, 2021

To do a text search on all fields, you first must create a text index on all fields.

As the mongodb documentation indicates, “To allow for text search on all fields with string content, use the wildcard specifier ($**) to index all fields that contain string content.”

if you are working inside the mongo shell (which you execute from the command line by calling ‘mongo’), then you can do it with this command, where ‘collection’ is the name of the collection in the db you want to use.

db.collection.createIndex({ "$**": "text" },{ name: "TextIndex" })

The second object, i.e. {name:"TextIndex"}, is optional. you don't actually need to give the index a name, since there can only be a single text index per collection (you can drop indexes and create new ones if you want).

once you have created a text index on all fields, you can do a simple text search with the following query object: { $text : { $search: <your string> } }

So, if you are writing a javascript function you might do something like:

var cursor = db.collection(<collection_name>).find({ $text: { $search: <your string> } });

For more info on the various ways to control the search, see the mongodb documentation on text searching here

--

--