Overview
In this guide, you can learn how to use the Rust driver to run MongoDB Search queries on a collection. MongoDB Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. MongoDB Search indexes specify the behavior of the search and which fields to index.
Sample Data
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.
Run a MongoDB Search Query
This section shows how to create an aggregation pipeline to run an MongoDB Search query on a collection.
To run an MongoDB Search query, you must create an MongoDB Search index on your
collection. To learn how to programmatically create an MongoDB Search index, see the
MongoDB 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 MongoDB Search index.
After you create an MongoDB 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.
MongoDB Search Example
This example runs an MongoDB Search query by performing the following actions:
Creates a
$searchstage that instructs the driver to query for documents in which thetitlefield contains the word"Alabama"Creates a
$projectstage that instructs the driver to include thetitlefield in the query resultsPasses the pipeline stages to the
aggregate()method and prints the results
use mongodb::{        bson::{doc, Document},        Client, Collection,    }; use futures::stream::TryStreamExt;   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 MongoDB 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" } 
MongoDB Search Metadata
Use the $searchMeta pipeline stage to create a $searchMeta aggregation stage, which returns
only the metadata from the MongoDB 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 MongoDB Search aggregation stage:
use mongodb::{     bson::{doc, Document, DateTime},     Client, Collection, }; use futures::stream::TryStreamExt; 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     }   ] } 
Create Pipeline Search Stages
The MongoDB Rust driver provides helper methods and builders for creating MongoDB Search pipeline stages. These helpers allow you to construct complex search queries using Rust's type system for better compile-time safety.
MongoDB Search Operators
The Rust driver supports the following MongoDB 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.  | 
Example Pipeline Search Stage
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 MongoDB 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 MongoDB Search indexes, see the MongoDB 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
MongoDB Search index.
The following code creates a $search stage that has the following
specifications:
Checks that the
genresarray includes"Comedy"Searches the
fullplotfield for the phrase"new york"Matches
yearvalues between1950and2000, inclusiveSearches for
titlevalues that begins with the term"Love"
use mongodb::{     bson::{doc, Document},     Client, Collection, }; use futures::stream::TryStreamExt; 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 MongoDB Search operators, see the MongoDB Search Operators documentation.
Type-Safe Query Construction
The MongoDB Rust Driver provides type-safe helper methods for constructing MongoDB Search queries. These helpers use Rust's type system to provide compile-time validation and better IDE support compared to raw BSON document construction.
The following example builds an autocomplete query with type safety by using the
atlas_search module:
use mongodb::atlas_search; let cursor = collection.aggregate(vec![     atlas_search::autocomplete("title", "pre")         .fuzzy(doc! { "maxEdits": 1, "prefixLength": 1, "maxExpansions": 256 })         .into_stage(),     doc! {         "$limit": 10,     },     doc! {         "$project": {             "_id": 0,             "title": 1,         }     }, ]).await?; 
The query in the preceding example performs the following operations:
Uses the
autocomplete()method to search for titles starting with"pre"Uses the
fuzzy()method to add tolerance for typos with specific parameters:maxEdits: Sets the maximum number of character changes allowed to1prefixLength: Sets the number of characters at the beginning that must match exactly to1maxExpansions: Sets the maximum number of variations to consider to256
Uses the
into_stage()method to generate the proper$searchBSON documentLimits the output to
10documentsReturns only the
titlefield, excluding_id
Additional Information
To learn more about MongoDB Search, see MongoDB Search in the Atlas documentation.
API Documentation
To learn more about the methods mentioned in this guide, see the following API documentation: