Advanced Text Search in MongoDB

Friday, March 10th 2023

Here are some advanced examples of text search in MongoDB:

  1. Searching for multiple terms with logical operators:
db.articles.find({ $text: { $search: "JavaScript AND (database OR backend)" } })

This query uses logical operators (AND and OR) to search for articles containing the words "JavaScript" and either "database" or "backend".

  1. Searching for exact phrases:
db.articles.find({ $text: { $search: "\"JavaScript framework\"" } })

This query uses double quotes to search for articles containing the exact phrase "JavaScript framework".

  1. Searching for word variants with stemming:
db.articles.find({ $text: { $search: "run" } })

By default, MongoDB's text search engine uses stemming to search for word variants. So this query will also match documents containing words like "running", "runner", and "runs".

  1. Searching in specific fields:
db.articles.find({ $text: { $search: "JavaScript" }, category: "Programming" })

This query searches for the word "JavaScript" only in documents where the category field is "Programming".

  1. Combining text search with other query operators:
db.articles.find({ $text: { $search: "JavaScript" }, publishedAt: { $gte: ISODate("2022-01-01"), $lte: ISODate("2022-12-31") } })

This query searches for the word "JavaScript" only in documents published in the year 2022.

  1. Adjusting relevance scoring with weights:
db.articles.find({ $text: { $search: "JavaScript", $weight: { title: 3, body: 1 } } })

This query adjusts the relevance scoring to give more weight to the title field (with a weight of 3) than to the body field (with a weight of 1). This can be useful when you want to prioritize matches in certain fields over others.

These are just a few examples of the advanced text search capabilities in MongoDB. With the right query operators and settings, you can fine-tune your search queries to find exactly the documents you need.