DEV Community

Spurgeon Gnan Prakasham Tara
Spurgeon Gnan Prakasham Tara

Posted on

How to do multiple indexed MongoDB text Search

Indexing Multiple Fields (Compound Indexing)
More often than not, you will be using text search on multiple fields of a document. In our example, we will enable compound text indexing on the subject and content fields. Go ahead and execute the following command in mongo shell:

db.messages.createIndex({"subject":"text","content":"text"})
Did this work? No!! Creating a second text index will give you an error message saying that a full-text search index already exists. Why is it so? The answer is that text indexes come with a limitation of only one text index per collection. Hence if you would like to create another text index, you will have to drop the existing one and recreate the new one.

db.messages.dropIndex("subject_text")
db.messages.createIndex({"subject":"text","content":"text"})

Top comments (2)

Collapse
 
spurgeonprakash profile image
Spurgeon Gnan Prakasham Tara

I Love Posting These Kinds of Posts

Collapse
 
spurgeonprakash profile image
Spurgeon Gnan Prakasham Tara

Nice Post