- MongoDB CRUD Operations >
- Text Search >
- Perform a Text Search (Legacy)
Perform a Text Search (Legacy)¶
MongoDB offers a full-text search solution, MongoDB Atlas Search, for data hosted on MongoDB Atlas. A legacy text search capability is available for users self-managing MongoDB deployments.
To run legacy text search queries, you must have a text
index on
your collection. MongoDB provides text indexes to support text search queries on string content.
text
indexes can include any field whose value is a string or an
array of string elements. A collection can only have one text
search index, but that index can cover multiple fields.
See the Text Indexes section for a full reference on text indexes, including behavior, tokenization, and properties.
Examples¶
This example demonstrates how to build a text index and use it to find coffee shops, given only text fields.
Create a Collection¶
Create a collection stores
with the following documents:
Create a Text Index¶
Run the following in mongosh
to allow text search over
the name
and description
fields:
Search for an Exact Phrase¶
You can also search for exact phrases by wrapping them in double-quotes.
If the $search
string includes a phrase and individual terms, text
search will only match documents that include the phrase.
For example, the following will find all documents containing “coffee shop”:
For more information, see Phrases.
Exclude a Term¶
To exclude a word, you can prepend a “-
” character. For example, to
find all stores containing “java” or “shop” but not “coffee”, use the
following:
Sort the Results¶
MongoDB will return its results in unsorted order by default. However, text search queries will compute a relevance score for each document that specifies how well a document matches the query.
To sort the results in order of relevance score, you must explicitly
project the $meta
textScore
field and sort on it:
Text search is also available in the aggregation pipeline.