π Construct Search Queries
You can construct Atlas Search queries with the $search
aggregation pipeline stage.
MongoDB aggregation pipelines are multi-stage "assembly lines" that reshape data and perform calculations. Pipelines can consist of one or more aggregation stages, performing different operations like match, group, sort, and output. For an exhaustive list of all available stages, visit the complete list of pipeline operators.
If you are not familiar with the aggregation pipelines, you should start with Advanced Querying With Aggregation Pipelines.
In this section, we'll build an aggregation pipeline with the $search
stage which performs full-text search using the Atlas Search index you just created.
Aggregations in the Atlas UIβ
Navigate to the Collections tab of your database deployment, pick the books
collection, and navigate to the Aggregation tab from the navbar under your collection details.
The Atlas UI can start feeling a bit cramped at this point. You can also use the aggregation pipeline builder in Compass for a better experience.
Click the Add Stage button and type $search in the select input.
Add the following code for the $search
stage.
{
index: "fulltextsearch",
text: {
query: "cooking",
path: ["title"]
}
}
The stage uses the "fulltextsearch" index. You don't need to explicitly define the index if it's "default" but you can keep it for clarity.
The text
operator will search for "cooking" in the title
field. You should see a collection of documents returned on the right.
Click the Add Stage button, scroll down, and select $project for Stage 2.
Add the following implementation for the $project
stage to filter the returned fields.
{
title: 1,
authors: 1,
genres: 1,
pages: 1
}
At this point, you should see similar results as what you did in the last section, as this is pretty much the same query.