MongoDB Text Indexes Example
Let’s look at some examples of Text Indexes in MongoDB to understand the concept better.
In this example, we will be working with
Database: gfg
Collection: studentsposts
Documents: Two documents
Now, Let us create a text index on “title” field of “studentsposts” collection in order to search inside the collection.
Query:
db.studentsposts.createIndex({title: "text"})
Output:
Now we will see how to search using Text Index:
Query:
db.studentsposts.find({$text:{$search: "mongodb"}}).pretty()
Output:
Output is self-explanatory above as we have created index on “title” field, and we have tried to search the text “mongodb”. It is present in both the documents in the “title” field. Hence, the result is 2 documents here.
MongoDB Text Indexes
The MongoDB Text Indexes feature allows users to perform full-text searches on text fields in a collection efficiently. It supports text search queries, enabling users to search for specific words or phrases within text fields.
Contact Us