Here are some advanced examples of text search in MongoDB:
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".
db.articles.find({ $text: { $search: "\"JavaScript framework\"" } })
This query uses double quotes to search for articles containing the exact phrase "JavaScript framework".
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".
db.articles.find({ $text: { $search: "JavaScript" }, category: "Programming" })
This query searches for the word "JavaScript" only in documents where the category
field is "Programming".
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.
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.