How to Use Atlas Search in MongoDB: Syntax and Examples
To use
Atlas Search in MongoDB, create a search index on your collection and run an $search aggregation stage in your query. This lets you perform full-text search with rich features like phrase, autocomplete, and fuzzy matching.Syntax
The basic syntax to use Atlas Search is within an aggregation pipeline using the $search stage. You specify the index name and the text operator with the query string and path to the field to search.
- $search: The aggregation stage to perform search.
- index: The name of the Atlas Search index.
- text: Operator for text search.
- query: The search string.
- path: The field(s) to search in.
mongodb
db.collection.aggregate([
{
$search: {
index: "default",
text: {
query: "search term",
path: "fieldName"
}
}
}
])Example
This example shows how to search for the word "coffee" in the description field of a products collection using the default Atlas Search index.
mongodb
db.products.aggregate([
{
$search: {
index: "default",
text: {
query: "coffee",
path: "description"
}
}
},
{
$limit: 3
}
])Output
[
{"_id": ObjectId("..."), "name": "Espresso Machine", "description": "High quality coffee maker."},
{"_id": ObjectId("..."), "name": "Coffee Beans", "description": "Freshly roasted coffee beans."},
{"_id": ObjectId("..."), "name": "Coffee Mug", "description": "Ceramic mug for coffee."}
]
Common Pitfalls
Common mistakes when using Atlas Search include:
- Not creating a search index before querying with
$search. - Using incorrect
pathvalues that don't match indexed fields. - Expecting
$searchto work like a simple$textsearch without configuring the index. - Not handling case sensitivity or tokenization properly in queries.
Always create and configure your search index in the Atlas UI or via API before running queries.
mongodb
/* Wrong: Querying without creating index */ db.products.aggregate([ { $search: { text: { query: "coffee", path: "description" } } } ]) /* Right: Specify index name after creating it */ db.products.aggregate([ { $search: { index: "default", text: { query: "coffee", path: "description" } } } ])
Quick Reference
Here is a quick reference for common $search operators:
| Operator | Description |
|---|---|
| text | Full-text search on string fields |
| autocomplete | Search with prefix matching for autocomplete |
| phrase | Search for exact phrases |
| compound | Combine multiple search conditions |
| range | Search numeric or date ranges |
| exists | Check if a field exists |
Key Takeaways
Create an Atlas Search index on your collection before querying.
Use the $search aggregation stage with the text operator to perform full-text search.
Specify the index name and the field path correctly in your query.
Atlas Search supports advanced features like autocomplete and phrase search.
Avoid running $search queries without an index to prevent errors.