Docs Menu
Docs Home
/ /

Run an Atlas Search Query

In this guide, you can learn how to use the Rust driver to run Atlas Search queries on a collection. Atlas Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. Atlas Search indexes specify the behavior of the search and which fields to index.

The example in this guide uses the movies collection in the sample_mflix database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.

This section shows how to create an aggregation pipeline to run an Atlas Search query on a collection.

To run an Atlas Search query, you must create an Atlas Search index on your collection. To learn how to programmatically create an Atlas Search index, see the Atlas Search and Vector Search Indexes section of the Indexes guide. You can replace the <search index name> placeholder in the code examples in this guide with the name of your Atlas Search index.

After you create an Atlas Search index, add the $search stage in your array of pipeline stages to specify the search criteria. Then, call the aggregate() method and pass your pipeline array as a parameter.

Tip

To learn more about aggregation operations, see the Aggregation guide.

This example runs an Atlas Search query by performing the following actions:

  • Creates a $search stage that instructs the driver to query for documents in which the title field contains the word "Alabama"

  • Creates a $project stage that instructs the driver to include the title field in the query results

  • Passes the pipeline stages to the aggregate() method and prints the results

use mongodb::{
bson::{doc, Document},
Client, Collection,
};
use futures::stream::TryStreamExt;
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
// Replace the uri string with your connection string
let uri = "<connection string uri>";
let client = Client::with_uri_str(uri).await?;
let my_coll: Collection<Document> = client
.database("sample_mflix")
.collection("movies");
// Defines the Atlas Search query
let pipeline = vec![
doc! {
"$search": {
"index": "<search index name>",
"text": {
"query": "Alabama",
"path": "title"
}
}
},
doc! {
"$project": {
"title": 1,
"_id": 1
}
}
];
// Runs the aggregation pipeline
let mut cursor = my_coll.aggregate(pipeline).await?;
// Prints the results
while let Some(doc) = cursor.try_next().await? {
println!("{}", doc);
}
Ok(())
}
{
"_id": ObjectId("..."),
"title": "Alabama Moon"
}
{
"_id": ObjectId("..."),
"title": "Crazy in Alabama"
}
{
"_id": ObjectId("..."),
"title": "Sweet Home Alabama"
}

Use the $searchMeta pipeline stage to create a $searchMeta aggregation stage, which returns only the metadata from the Atlas Search results.

Tip

Only Available on Atlas for MongoDB v4.4.11 and later

This aggregation pipeline operator is available only on MongoDB Atlas clusters running v4.4.11 and later.

The following example shows how to retrieve metadata for an Atlas Search aggregation stage:

use mongodb::{
bson::{doc, Document, DateTime},
Client, Collection,
};
use futures::stream::TryStreamExt;
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
// Replace the uri string with your connection string
let uri = "<connection string uri>";
let client = Client::with_uri_str(uri).await?;
let my_coll: Collection<Document> = client
.database("sample_mflix")
.collection("movies");
// Defines the $searchMeta pipeline stage
let pipeline = vec![
doc! {
"$searchMeta": {
"index": "<search index name>",
"near": {
"path": "released",
"origin": DateTime::parse_rfc3339_str("2011-09-01T00:00:00.000Z")
.unwrap(),
"pivot": 7776000000i64
}
}
}
];
let mut cursor = my_coll.aggregate(pipeline).await?;
while let Some(doc) = cursor.try_next().await? {
println!("{}", doc);
}
Ok(())
}
{
"count": 3,
"hits": [
{
"id": ObjectId("..."),
"score": 1.0
},
{
"id": ObjectId("..."),
"score": 1.0
},
{
"id": ObjectId("..."),
"score": 1.0
}
]
}

The MongoDB Rust driver provides helper methods and builders for creating Atlas Search pipeline stages. These helpers allow you to construct complex search queries using Rust's type system for better compile-time safety.

The Rust driver supports the following Atlas Search operators through BSON document construction:

Operator
Description

Performs a search for a word or phrase that contains a sequence of characters from an incomplete input string.

Combines two or more operators into a single query.

Checks whether a field matches a value you specify.

Tests if a path to a specified indexed field name exists in a document.

For geographic queries that allow search by location.

To return the snippets of text matching the search criteria, useful for user interfaces that need to highlight search terms.

Performs a search for an array of BSON number, date, boolean, objectId, uuid, or string values at the given path and returns documents where the value of the field equals any value in the specified array.

Returns documents similar to input documents.

Supports querying and scoring numeric, date, and GeoJSON point values.

Performs a search for documents containing an ordered sequence of terms by using the analyzer specified in the index configuration.

Supports querying a combination of indexed fields and values.

Supports querying and scoring numeric, date, and string values.

Interprets the query field as a regular expression.

Performs a full-text search by using the analyzer that you specify in the index configuration.

Enables queries which use special characters in the search string that can match any character.

Note

Atlas Sample Dataset

This example uses the sample_mflix.movies collection from the Atlas sample datasets. To learn how to set up a free-tier Atlas cluster and load the sample dataset, see the Get Started with Atlas tutorial in the Atlas documentation.

Before you can run this example, you must create an Atlas Search index on the movies collection that has the following definition:

{
"mappings": {
"dynamic": true,
"fields": {
"title": {
"analyzer": "lucene.keyword",
"type": "string"
},
"genres": {
"normalizer": "lowercase",
"type": "token"
}
}
}
}

To learn more about creating Atlas Search indexes, see the Atlas Search and Vector Search Indexes section of the Indexes guide.

You can replace the <search index name> placeholder in the code with the name of your Atlas Search index.

The following code creates a $search stage that has the following specifications:

  • Checks that the genres array includes "Comedy"

  • Searches the fullplot field for the phrase "new york"

  • Matches year values between 1950 and 2000, inclusive

  • Searches for title values that begins with the term "Love"

use mongodb::{
bson::{doc, Document},
Client, Collection,
};
use futures::stream::TryStreamExt;
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
// Replace the uri string with your connection string
let uri = "<connection string uri>";
let client = Client::with_uri_str(uri).await?;
let my_coll: Collection<Document> = client
.database("sample_mflix")
.collection("movies");
// Creates a complex search using multiple operators
let search_stage = doc! {
"$search": {
"index": "<search index name>",
"compound": {
"must": [
{
"equals": {
"path": "genres",
"value": "Comedy"
}
},
{
"phrase": {
"path": "fullplot",
"query": "new york"
}
},
{
"range": {
"path": "year",
"gte": 1950,
"lte": 2000
}
},
{
"wildcard": {
"path": "title",
"query": "Love*"
}
}
]
}
}
};
let project_stage = doc! {
"$project": {
"title": 1,
"year": 1,
"genres": 1,
"_id": 1
}
};
let pipeline = vec![search_stage, project_stage];
let mut cursor = my_coll.aggregate(pipeline).await?;
while let Some(doc) = cursor.try_next().await? {
println!("{}", doc);
}
Ok(())
}
{
"_id": ObjectId("..."),
"genres": ["Comedy", "Romance"],
"title": "Love at First Bite",
"year": 1979
}
{
"_id": ObjectId("..."),
"genres": ["Comedy", "Drama"],
"title": "Love Affair",
"year": 1994
}

To learn more about Atlas Search operators, see the Atlas Search Operators documentation.

To learn more about Atlas Search, see Atlas Search in the Atlas documentation.

To learn more about the methods mentioned in this guide, see the following API documentation:

Back

Indexes

On this page