In the last example, we put a combined index on the subject and content fields. But there can be scenarios where you want any text content in your documents to be searchable.
For example, consider storing emails in MongoDB documents. In the case of emails, all the fields, including Sender, Recipient, Subject and Body, need to be searchable. In such scenarios you can index all the string fields of your document using the $** wildcard specifier.
The query would go something like this (make sure you are deleting the existing index before creating a new one):
db.messages.createIndex({"$**":"text"})
This query would automatically set up text indexes on any string fields in our documents. To test this out, insert a new document with a new field location in it:
db.messages.insert({"subject":"Birds can cook", "content":"Birds do not eat rats", "likes": 12, "year":2013, location: "Chicago", "language":"english"})
Now if you try text searching with keyword chicago (query below), it will return the document which we just inserted.
db.messages.find({$text: {$search: "chicago"}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})
A few things I would like to focus on here:
- Observe that we did not explicitly define an index on the
locationfield after we inserted a new document. This is because we already have defined a text index on the entire document using the$**operator. - Wildcard indexes can be slow at times, especially in scenarios where your data is very large. For this reason, plan your document indexes (aka wildcard indexes) wisely, as it can cause a performance hit.
Source: https://code.tutsplus.com/tutorials/full-text-search-in-mongodb--cms-24835