Skip to content

Instantly share code, notes, and snippets.

@bashkirtsevich
Last active April 13, 2023 01:03
Show Gist options
  • Select an option

  • Save bashkirtsevich/3066bb82b311926ccd2e8f6d2079a558 to your computer and use it in GitHub Desktop.

Select an option

Save bashkirtsevich/3066bb82b311926ccd2e8f6d2079a558 to your computer and use it in GitHub Desktop.
MongoDB Indexing the Entire Document (Wildcard Indexing)

Indexing the Entire Document (Wildcard Indexing)

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 location field 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment