### Example: Search for a Phrase in Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/text-search.txt This example demonstrates searching for documents where the 'description' field contains the specific phrase 'serves 2'. ```rust Dish { name: "Shepherd’s Pie", description: "A vegetarian take on the classic dish that uses lentils as a base. Serves 2." } Dish { name: "Garlic Butter Trout", description: "Baked trout seasoned with garlic, lemon, dill, and, of course, butter. Serves 2." } ``` -------------------------------- ### Sample Data for MongoDB Rust Driver Examples Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/retrieve.txt These are the sample documents used in the retrieval examples. Each document represents an inventory item. ```rust use mongodb::bson::{doc, Document}; fn get_sample_documents() -> Vec { vec![ doc! { "item": 1, "type": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" }, doc! { "item": 2, "type": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" }, doc! { "item": 3, "type": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" }, doc! { "item": 4, "type": "planner", "qty": 75, "size": { "h": 12.5, "w": 17, "uom": "cm" }, "status": "D" }, doc! { "item": 5, "type": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }, ] } ``` -------------------------------- ### CommandStartedEvent Example Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/monitoring/command-monitoring.txt Sample document representing a CommandStartedEvent, which is created when a command begins execution. ```none CommandStartedEvent { request_id: 12, db: "testdb", command_name: "find", connection: ..., command: ..., service_id: ... } ``` -------------------------------- ### Sample Documents - Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/query.txt Provides sample documents representing fruit inventory, used for query examples. ```rust let sample_docs = vec![ Fruit { id: ObjectId::parse_hex("60a5f1f1b1f1f1f1f1f1f1f1")?, name: "apple".to_string(), quantity: 100, description: Some("A crisp, sweet fruit.".to_string()), vendors: Some(vec!["A".to_string(), "B".to_string()]), }, Fruit { id: ObjectId::parse_hex("60a5f1f1b1f1f1f1f1f1f1f2")?, name: "banana".to_string(), quantity: 150, description: None, vendors: Some(vec!["B".to_string(), "C".to_string()]), }, Fruit { id: ObjectId::parse_hex("60a5f1f1b1f1f1f1f1f1f1f3")?, name: "orange".to_string(), quantity: 80, description: Some("A citrus fruit.".to_string()), vendors: Some(vec!["A".to_string(), "C".to_string()]), }, Fruit { id: ObjectId::parse_hex("60a5f1f1b1f1f1f1f1f1f1f4")?, name: "pear".to_string(), quantity: 28, description: None, vendors: Some(vec!["A".to_string(), "C".to_string()]), }, ]; ``` -------------------------------- ### Add Rocket and JSON Feature Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/web-app-tutorial.txt Install the Rocket web framework with JSON support. ```bash cargo add -F json rocket ``` -------------------------------- ### Console Output: MongoDB Command Tracing Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/tracing-logging.txt Example console output demonstrating debug-level tracing for MongoDB commands, including command start and success events with details like request ID and duration. ```console 2023-07-21T17:37:13.587794Z DEBUG mongodb::command: Command started topologyId="..." command="{\"insert\":\"test_coll\", ...}" databaseName="test" commandName="insert" requestId=12 driverConnectionId=1 serverConnectionId=133839 serverHost="..." serverPort=27017 2023-07-21T17:37:13.630401Z DEBUG mongodb::command: Command succeeded topologyId="..." reply="{\"n\":1, ...}" commandName="insert" requestId=12 driverConnectionId=1 serverConnectionId=133839 serverHost="..." serverPort=27017 durationMS=42 ``` -------------------------------- ### Sample Data Structure - Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/query.txt Defines the structure for fruit inventory documents used in query examples. ```rust #[derive(Debug, Serialize, Deserialize)] struct Fruit { #[serde(rename = "_id")] id: ObjectId, name: String, quantity: u32, description: Option, vendors: Option>, } ``` -------------------------------- ### CommandFailedEvent Example Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/monitoring/command-monitoring.txt Sample document representing a CommandFailedEvent, which is created when a command does not succeed. ```none CommandFailedEvent { duration: ..., command_name: "find", failure: ..., request_id: 12, connection: ..., service_id: ... } ``` -------------------------------- ### Sample Documents for Aggregation Examples Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/aggregation.txt These JSON documents represent user profiles and are used in the aggregation examples. They contain user information such as name, age, genre interests, and last active date. ```json { "name": "Sonya Mehta", "age": 23, "genre_interests": ["fiction", "mystery", "memoir"], "last_active": { "$date": "2023-05-13T00:00:00.000Z" } } ``` ```json { "name": "Selena Sun", "age": 45, "genre_interests": ["fiction", "literary", "theory"], "last_active": { "$date": "2023-05-25T00:00:00.000Z" } } ``` ```json { "name": "Carter Johnson", "age": 56, "genre_interests": ["literary", "self help"], "last_active": { "$date": "2023-05-31T00:00:00.000Z" } } ``` ```json { "name": "Rick Cortes", "age": 18, "genre_interests": ["sci-fi", "fantasy", "memoir"], "last_active": { "$date": "2023-07-01T00:00:00.000Z" } } ``` -------------------------------- ### Run Cargo Application Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/web-app-tutorial.txt Command to start the Rust application using Cargo. ```bash cargo run ``` -------------------------------- ### Enable Network Compression via ClientOptions Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/connections/network-compression.txt Configure network compression by setting the 'compressors' field in a ClientOptions instance. This example uses Snappy compression with a default level. ```rust use mongodb::options::Compressor; let mut client_options = ClientOptions::new(); client_options.compressors = Some(vec![Compressor::Snappy]); let client = Client::with_options(client_options).await?; ``` -------------------------------- ### CommandSucceededEvent Example Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/monitoring/command-monitoring.txt Sample document representing a CommandSucceededEvent, which is created when a command completes successfully. ```none CommandSucceededEvent { duration: ..., reply: ..., command_name: "find", request_id: 12, connection: ..., service_id: ... } ``` -------------------------------- ### Insert Sample Data - Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/skip.txt Inserts sample `Book` documents into the `books` collection. This data is used in subsequent examples. ```rust let books = vec![ Book { id: None, name: "A Dance with Dragons".to_string(), author: "Martin".to_string(), length: 1104 }, Book { id: None, name: "Atlas Shrugged".to_string(), author: "Rand".to_string(), length: 1088 }, Book { id: None, name: "Les Misérables".to_string(), author: "Hugo".to_string(), length: 1462 }, Book { id: None, name: "The Lord of the Rings".to_string(), author: "Tolkien".to_string(), length: 1178 }, Book { id: None, name: "The Stand".to_string(), author: "King".to_string(), length: 1152 }, ]; collection.insert_many(books, None).await.expect("failed to insert documents"); ``` -------------------------------- ### Sample Documents for Compound Operations Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/compound-operations.txt These JSON documents represent sample student data used in the compound operation examples. ```json { "name": "Alex Johnson", "age": 8, "school": "Lakeside Elementary" } ``` ```json { "name": "Samara Khan", "age": 11, "school": "Rolling Hills Middle School" } ``` ```json { "name": "Ben Joseph", "age": 16, "school": "Aurora High School" } ``` ```json { "name": "Deanna Porowski", "age": 10, "school": "Lakeside Elementary" } ``` -------------------------------- ### Change Event Output with Pre-Image Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/change-streams.txt Example change event output demonstrating the pre-image of a document after an update operation. It includes the document's state before the change. ```text Operation performed: Update Pre-image: Some(Director { name: "Jane Campion", movies: ["The Piano", "Bright Star"], oscar_noms: 5 }) ``` -------------------------------- ### Insert Sample Data into Books Collection Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/sort.txt Inserts sample book documents into the 'books' collection to be used for sorting examples. ```rust let books = vec![ Book::new(1, "The Brothers Karamazov", "Dostoevsky", 824), Book::new(2, "Atlas Shrugged", "Rand", 1088), Book::new(3, "Les Miserables", "Hugo", 1462), Book::new(4, "A Dance with Dragons", "Martin", 1104), ]; let mut docs = Vec::new(); for book in books { docs.push(doc! { "_id" => book._id, "name" => book.name, "author" => book.author, "length" => book.length, }); } collection.insert_many(docs, None).await.expect("Failed to insert sample data"); ``` -------------------------------- ### Perform find_one_and_replace with Projection and ReturnDocument Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/compound-operations.txt This example demonstrates calling `find_one_and_replace()` with a query filter, a replacement document, and chaining `return_document()` and `projection()` methods to control the output. ```rust collection.find_one_and_replace( doc! { "name": "Johnson" }, doc! { "name": "Toby Fletcher", "school": "Durango High School" }, FindOneAndReplaceOptions::builder() .return_document(ReturnDocument::After) .projection(doc! { "name": 1, "school": 1 }) .build(), ) .await?; ``` -------------------------------- ### Update Operation Output Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/change-streams.txt Example output showing the result of an update operation when pre-images are enabled. It details the fields that were updated. ```text Update performed: Some(UpdateDescription { updated_fields: Document({ "oscar_noms": Int64(2)}), removed_fields: [], truncated_arrays: Some([]) }) ``` -------------------------------- ### Add serde_json Crate Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/web-app-tutorial.txt Installs the `serde_json` crate using Cargo to handle JSON serialization and deserialization for API responses and requests. ```bash cargo add serde_json ``` -------------------------------- ### Insert Sample Book Data into MongoDB Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/limit.txt Inserts sample Book documents into the 'books' collection. This data is used for demonstration purposes in the guide. ```rust let books = vec![ Book { name: "The Brothers Karamazov".to_string(), author: "Dostoyevsky".to_string(), length: 824 }, Book { name: "War and Peace".to_string(), author: "Tolstoy".to_string(), length: 1225 }, Book { name: "Atlas Shrugged".to_string(), author: "Rand".to_string(), length: 1088 }, Book { name: "A Dance with Dragons".to_string(), author: "Martin".to_string(), length: 1104 }, Book { name: "The Lord of the Rings".to_string(), author: "Tolkien".to_string(), length: 1178 }, ]; let mut book_docs = Vec::new(); for book in books { book_docs.push(book.into()); } collection.insert_many(book_docs, None).await?; ``` -------------------------------- ### Console Output: MongoDB Connection Logs Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/tracing-logging.txt Example console output showing debug-level logs for MongoDB connection pool creation, readiness, and checkout events when tracing is enabled. ```console [2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection pool created topologyId="..." serverHost="..." serverPort=27017 [2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection pool created topologyId="..." serverHost="..." serverPort=27017 [2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection pool created topologyId="..." serverHost="..." serverPort=27017 [2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection pool ready topologyId="..." serverHost="..." serverPort=27017 [2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection checkout started topologyId="..." serverHost="..." serverPort=27017 [2023-07-21T18:13:00Z DEBUG mongodb::connection] Connection created topologyId="..." serverHost="..." serverPort=27017 driverConnectionId=1 ... ``` -------------------------------- ### Specify read preference for 'hello' command Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/run-command.txt Set a read preference for command execution by chaining the `selection_criteria()` method. This example specifies the `Primary` read preference for the 'hello' command. ```rust let result = my_db .run_command(doc! { "hello": 1 }) .selection_criteria(SelectionCriteria::ReadPreference(ReadPreference::Primary)) .await?; ``` -------------------------------- ### Connect with authSource Parameter Source: https://github.com/mongodb/docs-rust/blob/master/source/connection-troubleshooting.txt Example of creating a MongoDB client with a connection string that specifies the `authSource` parameter. This is useful when your user is defined in a database other than the one you are connecting to. ```rust let uri = "mongodb://:@:/?authSource=users"; let client = Client::with_uri_str(uri).await?; ``` -------------------------------- ### Subscribe to SDAM Events in Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/monitoring/cluster-monitoring.txt Connect to a MongoDB deployment and subscribe to Server Discovery and Monitoring (SDAM) events by assigning an EventHandler. This example prints each event to the console. ```rust use mongodb::options::ClientOptions; use mongodb::event::{EventHandler, ServerDescriptionChangedEvent, ServerOpeningEvent, ServerClosedEvent, TopologyDescriptionChangedEvent, TopologyOpeningEvent, TopologyClosedEvent, ServerHeartbeatStartedEvent, ServerHeartbeatSucceededEvent, ServerHeartbeatFailedEvent}; use std::sync::{Arc, Mutex}; #[tokio::main] async fn main() -> mongodb::error::Result<()> { let mut client_options = ClientOptions::parse("mongodb://localhost:27017").await?; // Define a custom event handler let handler = Arc::new(Mutex::new(MyEventHandler {})); client_options.sdam_event_handler = Some(handler); // Connect to MongoDB let client = mongodb::Client::with_options(client_options)?; // Keep the client alive to receive events // In a real application, you would have a longer-running process tokio::time::sleep(tokio::time::Duration::from_secs(60)).await; Ok(()) } struct MyEventHandler; impl EventHandler for MyEventHandler { fn handle_server_description_changed_event( &self, event: ServerDescriptionChangedEvent, ) { println!("Server description changed: {:?}", event); } fn handle_server_opening_event(&self, event: ServerOpeningEvent) { println!("Server opening: {:?}", event); } fn handle_server_closed_event(&self, event: ServerClosedEvent) { println!("Server closed: {:?}", event); } fn handle_topology_description_changed_event( &self, event: TopologyDescriptionChangedEvent, ) { println!("Topology description changed: {:?}", event); } fn handle_topology_opening_event(&self, event: TopologyOpeningEvent) { println!("Topology opening: {:?}", event); } fn handle_topology_closed_event(&self, event: TopologyClosedEvent) { println!("Topology closed: {:?}", event); } fn handle_server_heartbeat_started_event( &self, event: ServerHeartbeatStartedEvent, ) { println!("Server heartbeat started: {:?}", event); } fn handle_server_heartbeat_succeeded_event( &self, event: ServerHeartbeatSucceededEvent, ) { println!("Server heartbeat succeeded: {:?}", event); } fn handle_server_heartbeat_failed_event( &self, event: ServerHeartbeatFailedEvent, ) { println!("Server heartbeat failed: {:?}", event); } } ``` -------------------------------- ### Sample Data for Delete Operations Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/write-operations/delete.txt This JSON represents sample documents used in delete operation examples. Each document includes item name, category, and unit price. ```json { "item": "trowel", "category": "garden", "unit_price": 9.89 }, { "item": "placemat", "category": "kitchen", "unit_price": 3.19 }, { "item": "watering can", "category": "garden", "unit_price": 11.99 } ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-start/download-and-install.txt Change your current directory to the newly created 'rust_quickstart' project directory. ```bash cd rust_quickstart ``` -------------------------------- ### Create New Rust Project Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-start/download-and-install.txt Use this command to create a new Rust project directory named 'rust_quickstart'. This command generates a Cargo.toml file and a src directory with a main.rs file. ```bash cargo new rust_quickstart ``` -------------------------------- ### Count Documents Synchronously in Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/usage-examples/count.txt Use `estimated_document_count()` to get the total number of documents and `count_documents()` with a filter to count matching documents in a synchronous Rust application. Ensure you have the necessary MongoDB client and collection setup. ```rust let filter = doc! {}; let count_options = CountOptions::builder().filter(filter).build(); let total_documents = collection.estimated_document_count(None)?; let matching_documents = collection.count_documents(doc! {}, None)?; println!("Number of documents: {}", total_documents); println!("Number of matching documents: {}", matching_documents); ``` -------------------------------- ### Running the 'explain' Command Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/run-command.txt This example demonstrates how to use the `run_command()` method to execute the `explain` command for a `count` operation on the `flowers` collection in the `plants` database. The `explain` command is run in the `"queryPlanner"` verbosity mode. ```APIDOC ## POST /api/db/runCommand ### Description Executes a database command. ### Method POST ### Endpoint `db.runCommand()` ### Parameters #### Request Body - **command** (object) - Required - The command to run. Example: `{"count": "flowers"}` - **options** (object) - Optional - Options for running the command. - **verbosity** (string) - Optional - The verbosity mode for the explain command. Example: `"queryPlanner"` ### Request Example ```json { "command": { "count": "flowers", "$db": "plants" }, "options": { "verbosity": "queryPlanner" } } ``` ### Response #### Success Response (200) - **ok** (integer) - Indicates if the command succeeded (1) or failed (0). - **operationTime** (object) - The logical time of the operation. - **$clusterTime** (object) - A document containing the signed cluster time. - **queryPlanner** (object) - Details about the query execution plan. #### Response Example ```json { "$clusterTime": { "clusterTime": { "T": 1673969525, "I": 24 }, "signature": {...} }, "command": { "$db": "plants", "count": "flowers" }, "explainVersion": "1", "ok": 1, "operationTime": { "T": 1673969525, "I": 24 }, "queryPlanner": { "indexFilterSet": false, "maxIndexedAndSolutionsReached": false, "maxIndexedOrSolutionsReached": false, "maxScansToExplodeReached": false, "namespace": "plants.flowers", "rejectedPlans": [], "winningPlan": { "stage": "RECORD_STORE_FAST_COUNT" } }, "serverInfo": {...}, "serverParameters": { "internalDocumentSourceGroupMaxMemoryBytes": 104857600, ... } } ``` ``` -------------------------------- ### Count Documents Asynchronously in Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/usage-examples/count.txt Use `estimated_document_count()` to get the total number of documents and `count_documents()` with a filter to count matching documents in an asynchronous Rust application. Ensure you have the necessary MongoDB client and collection setup. ```rust let filter = doc! {}; let count_options = CountOptions::builder().filter(filter).build(); let total_documents = collection.estimated_document_count(None).await?; let matching_documents = collection.count_documents(doc! {}, None).await?; println!("Number of documents: {}", total_documents); println!("Number of matching documents: {}", matching_documents); ``` -------------------------------- ### Create Rust Project Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/web-app-tutorial.txt Run these commands to create a new Rust project and navigate into its directory. ```bash cargo new rust-crud-app cd rust-crud-app ``` -------------------------------- ### Define Book Struct for Sorting Examples Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/sort.txt This struct defines the model for documents in the 'books' collection, used in sorting examples. ```rust use mongodb::bson::{doc, Document}; #[derive(Debug)] struct Book { _id: i32, name: String, author: String, length: u32, } impl Book { fn new(id: i32, name: &str, author: &str, length: u32) -> Self { Book { _id: id, name: name.to_string(), author: author.to_string(), length } } } ``` -------------------------------- ### Initialize Database Connection in main.rs Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/web-app-tutorial.txt Initializes the database connection and attaches it to the Rocket application. The `mount()` function is left with placeholder arguments initially. ```rust mod db; mod models; mod routes; use rocket::{launch, routes}; use rocket_db_pools::Database; #[launch] fn rocket() -> _ { rocket::build() .attach(db::MainDatabase::init()) .mount() ``` -------------------------------- ### Run the 'hello' command Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/run-command.txt Use the `run_command()` method to execute a database command like 'hello'. This command returns information about the current member's role in the replica set. ```rust let result = my_db.run_command(doc! { "hello": 1 }).await?; ``` -------------------------------- ### Example: Exclude Terms from Text Search in Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/text-search.txt This example searches for documents containing 'vegan' but excludes any documents that also contain 'tofu'. ```rust Dish { name: "Kale Tabbouleh", description: "A bright, herb-based salad. A perfect starter for vegetarians and vegans." } ``` -------------------------------- ### Create MongoDB Client with Default Connection Settings Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/performance.txt Shows how to initialize a MongoDB Client using the default connection settings, which includes automatic management of connection pooling, server topology discovery, and monitoring. ```rust let client = Client::with_uri_str("").await?; ``` -------------------------------- ### Test Get Recipes Route with cURL Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/web-app-tutorial.txt Uses cURL to send a GET request to the /recipes endpoint to retrieve all recipes. Expects a JSON array of recipes. ```bash curl -v --header "Content-Type: application/json" --header "Accept: application/json" http://127.0.0.1:8000/recipes/ ``` -------------------------------- ### Define Dish Struct for Text Search Examples Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/text-search.txt Defines the `Dish` struct used as a model for documents in the `menu` collection for text search examples. Ensure this struct is defined before using it in text search operations. ```rust use mongodb::bson::{doc, oid::ObjectId}; #[derive(Debug, Serialize, Deserialize)] struct Dish { #[serde(rename = "_id", skip_serializing_if = "Option::is_none")] id: Option, name: String, description: String, } ``` -------------------------------- ### Example WriteError for Schema Validation Failure Source: https://github.com/mongodb/docs-rust/blob/master/source/op-error-handling.txt This example shows a typical WriteError message encountered when a document fails schema validation. The 'message' field indicates the validation failure, and the 'details' field provides specific information about the failing document and the validation rule that was violated. ```none Error: Error { kind: Write(WriteError(WriteError { code: 121, code_name: None, message: "Document failed validation", details: Some(Document({"failingDocumentId": Int32(1), "details": Document({"operatorName": String("$jsonSchema"), "title": String("Numerical Validation"), "schemaRulesNotSatisfied": Array(...)})})) })), labels: {}, wire_version: None, source: None } ``` -------------------------------- ### Execute Transaction with Callback (Rust) Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/transactions.txt This code snippet demonstrates how to start a client session, initiate a transaction, and then execute a callback function (insert_media) within that transaction using the `and_run` method. It automatically commits the transaction if the callback succeeds. ```rust let mut session = client.start_session().await?; let mut transaction_options = TransactionOptions::new(); transaction_options.read_concern(ReadConcern::majority()); transaction_options.write_concern(WriteConcern::majority()); transaction_options.read_preference(ReadPreference::primary()); session.start_transaction(transaction_options).await?; let result = session.and_run(insert_media).await?; println!("Successfully committed transaction!"); ``` -------------------------------- ### Configure Network Compression in Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/connections/network-compression.txt Specify Snappy, Zlib, and Zstandard as compressors for a MongoDB connection. Higher compression levels result in more compression but slower performance. This example highlights lines 4-8 and 10 for compressor configuration. ```rust use mongodb::options::Compressor; use mongodb::options::ClientOptions; // ... let mut client_options = ClientOptions::parse("mongodb://localhost:27017").await?; // Specify Snappy, Zlib, and Zstandard compressors. client_options.compressors = Some(vec![Compressor::Snappy, Compressor::Zlib, Compressor::Zstandard(3)]); // Connect to MongoDB with the configured options. let client = mongodb::Client::with_options(client_options).await?; // ... ``` -------------------------------- ### Define Database Connection in Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/web-app-tutorial.txt Sets up a MongoDB client and attaches it to the Rocket instance. Ensure the database name in `Rocket.toml` matches the `#[database("db")]` attribute. ```rust use rocket_db_pools::{mongodb::Client, Database}; #[derive(Database)] #[database("db")] pub struct MainDatabase(Client); ``` -------------------------------- ### Count Documents (Sync) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Count the number of documents that match the filter. This example uses the synchronous runtime. ```rust collection.count_documents(doc! { "status": "pending" })?; ``` -------------------------------- ### Count Documents (Async) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Count the number of documents that match the filter. This example uses the asynchronous runtime. ```rust collection.count_documents(doc! { "status": "pending" }).await?; ``` -------------------------------- ### Connect to MongoDB with Atlas Connection String (Sync) Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/connections/connection-guide.txt Use this synchronous example to connect to MongoDB Atlas using a connection string and enable the stable API. Ensure you have the necessary dependencies and a valid Atlas connection string. ```rust use mongodb::{options::ClientOptions, Client}; fn main() -> mongodb::error::Result<()> { // Load the Atlas connection string from an environment variable // or replace it with your Atlas connection string. let mut client_options = ClientOptions::parse(std::env::var("MONGODB_ATLAS_URI").unwrap())?; // Set the application name, optional client_options.app_name = Some("My app".to_string()); // Set the stable API version, optional client_options.stable_api = Some(mongodb::options::StableApi::new( "1.0".to_string(), )); // Create a new client and connect to the server let client = Client::with_options(client_options)?; // Define database and collection names let db = client.database("sample_mflix"); let collection = db.collection::("movies"); // Ping the server to see if you can connect to the instance client .database("admin") .run_command(mongodb::bson::doc! {"ping": 1}, None) .sync_deserialize()?; println!("Connected to MongoDB!"); // Example: Find a movie let filter = mongodb::bson::doc! { "title": "Back to the Future" }; match collection.find_one(filter, None)? { Some(movie) => println!("Found movie: {:?}", movie.get("title").unwrap()), None => println!("Movie not found."), } Ok(()) } ``` -------------------------------- ### Create Reusable MongoDB Client Instance Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/performance.txt Demonstrates creating a method that accepts a pointer to an existing Client instance for reuse across multiple requests, improving performance by avoiding repeated client creation. ```rust use mongodb::Client; // Assume client is an existing, connected Client instance // let client = Client::with_uri_str("").await?; async fn perform_operation(client: &Client) -> mongodb::error::Result<()> { // Perform database operations using the provided client let db = client.database("my_database"); let collection = db.collection::("my_collection"); // ... your operations here ... Ok(()) } ``` -------------------------------- ### Connect to MongoDB with Atlas Connection String (Async) Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/connections/connection-guide.txt Use this asynchronous example to connect to MongoDB Atlas using a connection string and enable the stable API. Ensure you have the necessary dependencies and a valid Atlas connection string. ```rust use mongodb::{options::ClientOptions, Client}; #[tokio::main] async fn main() -> mongodb::error::Result<()> { // Load the Atlas connection string from an environment variable // or replace it with your Atlas connection string. let mut client_options = ClientOptions::parse(std::env::var("MONGODB_ATLAS_URI").unwrap()).await?; // Set the application name, optional client_options.app_name = Some("My app".to_string()); // Set the stable API version, optional client_options.stable_api = Some(mongodb::options::StableApi::new( "1.0".to_string(), )); // Create a new client and connect to the server let client = Client::with_options(client_options)?; // Define database and collection names let db = client.database("sample_mflix"); let collection = db.collection::("movies"); // Ping the server to see if you can connect to the instance client .database("admin") .run_command(mongodb::bson::doc! {"ping": 1}, None) .await?; println!("Connected to MongoDB!"); // Example: Find a movie let filter = mongodb::bson::doc! { "title": "Back to the Future" }; match collection.find_one(filter, None).await? { Some(movie) => println!("Found movie: {:?}", movie.get("title").unwrap()), None => println!("Movie not found."), } Ok(()) } ``` -------------------------------- ### Create Various MongoDB Indexes in Rust Source: https://context7.com/mongodb/docs-rust/llms.txt Demonstrates creating single-field, compound, unique, text, and geospatial indexes. Also shows how to drop an index and create a clustered collection. ```rust use bson::{doc, Document}; use mongodb::{options::{ClusteredIndex, IndexOptions}, Client, Collection, IndexModel}; #[tokio::main] async fn main() -> mongodb::error::Result<()> { let client = Client::with_uri_str("mongodb://localhost:27017").await?; let my_coll: Collection = client.database("sample_training").collection("zips"); // Create single-field index let index = IndexModel::builder().keys(doc! { "city": 1 }).build(); let idx = my_coll.create_index(index).await?; println!("Created index: {}", idx.index_name); // Create compound index let index = IndexModel::builder() .keys(doc! { "city": 1, "pop": -1 }) .build(); let idx = my_coll.create_index(index).await?; println!("Created index: {}", idx.index_name); // Create unique index let opts = IndexOptions::builder().unique(true).build(); let index = IndexModel::builder() .keys(doc! { "email": 1 }) .options(opts) .build(); let idx = my_coll.create_index(index).await?; // Create text index with language option let idx_opts = IndexOptions::builder() .default_language("spanish".to_string()) .build(); let index = IndexModel::builder() .keys(doc! { "body": "text" }) .options(idx_opts) .build(); let idx = my_coll.create_index(index).await?; // Create geospatial 2dsphere index let index = IndexModel::builder() .keys(doc! { "location.geo": "2dsphere" }) .build(); let idx = my_coll.create_index(index).await?; // Drop an index my_coll.drop_index("city_1".to_string()).await?; // Create clustered collection let db = client.database("sample_training"); let cl_idx = ClusteredIndex::default(); db.create_collection("items").clustered_index(cl_idx).await?; Ok(()) } ``` -------------------------------- ### Access Data from a Cursor as an Array (Sync) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Collect all results from a query into a vector. This example uses the synchronous runtime. ```rust let docs: Vec<_> = collection.find(doc! { "status": "pending" })?.try_collect()?; println!("{:?}", docs); ``` -------------------------------- ### Create an Index (Sync) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Use the `create_index` method on a collection to create an index in the sync runtime. This operation takes an index model as an argument. ```rust use mongodb::bson::Document; use mongodb::options::IndexOptions; use mongodb::IndexModel; let mut options = IndexOptions::default(); options.unique = true; let model = IndexModel::builder() .keys(doc! { "x": 1 }) .options(options) .build(); collection.create_index(model, None).unwrap(); ``` -------------------------------- ### Access Data from a Cursor as an Array (Async) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Collect all results from a query into a vector. This example uses the asynchronous runtime. ```rust let docs: Vec<_> = collection.find(doc! { "status": "pending" }).await?.try_collect().await?; println!("{:?}", docs); ``` -------------------------------- ### Run `explain` Command with `run_command()` in Rust Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/run-command.txt Use the `run_command()` method to execute the `explain` command for a `count` operation on the `flowers` collection in the `plants` database. This example specifies the `queryPlanner` verbosity mode. ```rust use mongodb::{bson::doc, Client, Database}; use mongodb::options::ClientOptions; #[tokio::main] async fn main() -> mongodb::error::Result<()> { // Set up client options let mut client_options = ClientOptions::parse("mongodb://localhost:27017").await?; // Manually set the server_api so that the driver does not assume a default // server_api version when connecting to a MongoDB deployment. client_options.server_api = Some(ServerApi::builder().version(ServerApiVersion::V1).build()); let client = Client::with_options(client_options)?; // Get a handle to the database and collection let database = client.database("plants"); let collection = database.collection::("flowers"); // Define the command to run let command = doc! { "count": "flowers", "query": {{}}, "explain": {{ "verbosity": "queryPlanner" }} }; // Run the command let result = database.run_command(command, None).await?; println!("{}", bson::to_json(&result)); Ok(()) } ``` -------------------------------- ### Delete Multiple Documents (Sync) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Use to delete all documents that match the filter. This example uses the synchronous runtime. ```rust collection.delete_many(doc! { "status": "pending" })?; ``` -------------------------------- ### Connect to MongoDB with Stable API Source: https://context7.com/mongodb/docs-rust/llms.txt Establishes a connection to MongoDB using a connection URI and configures the Stable API. The `Client` should be reused. ```rust use mongodb::{ bson::doc, options::{ClientOptions, ServerApi, ServerApiVersion}, Client, }; #[tokio::main] async fn main() -> mongodb::error::Result<()> { // Replace with your MongoDB connection string let uri = "mongodb+srv://username:password@cluster.mongodb.net/?retryWrites=true&w=majority"; let mut client_options = ClientOptions::parse(uri).await?; // Set the server_api field to Stable API version 1 let server_api = ServerApi::builder().version(ServerApiVersion::V1).build(); client_options.server_api = Some(server_api); // Create a new client and connect to the server let client = Client::with_options(client_options)?; // Send a ping to confirm a successful connection client.database("admin").run_command(doc! { "ping": 1 }).await?; println!("Pinged your deployment. You successfully connected to MongoDB!"); Ok(()) } ``` -------------------------------- ### Delete Multiple Documents (Async) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Use to delete all documents that match the filter. This example uses the asynchronous runtime. ```rust collection.delete_many(doc! { "status": "pending" }).await?; ``` -------------------------------- ### Delete a Document (Sync) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Use to delete a single document that matches the filter. This example uses the synchronous runtime. ```rust collection.delete_one(doc! { "_id": 1 })?; ``` -------------------------------- ### Delete a Document (Async) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Use to delete a single document that matches the filter. This example uses the asynchronous runtime. ```rust collection.delete_one(doc! { "_id": 1 }).await?; ``` -------------------------------- ### Enable Network Compression via Connection String Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/connections/network-compression.txt Enable Snappy, Zlib, and Zstandard compression by specifying the 'compressors' parameter in the MongoDB connection string. ```rust let uri = "mongodb+srv://:@/?compressors=snappy,zlib,zstd"; let client = Client::with_uri_str(uri).await?; ``` -------------------------------- ### Replace a Document (Sync) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Use to replace a single document that matches the filter. This example uses the synchronous runtime. ```rust collection.replace_one(doc! { "_id": 1 }, doc! { "_id": 1, "name": "new name" })?; ``` -------------------------------- ### Replace a Document (Async) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Use to replace a single document that matches the filter. This example uses the asynchronous runtime. ```rust collection.replace_one(doc! { "_id": 1 }, doc! { "_id": 1, "name": "new name" }) .await?; ``` -------------------------------- ### ServerOpeningEvent Structure Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/monitoring/cluster-monitoring.txt Indicates that a connection to an instance, like a replica set member, has been opened. This is a sample output format. ```none ServerOpeningEvent { address: ..., topology_id: ... } ``` -------------------------------- ### Add Rocket DB Pools Crate Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/web-app-tutorial.txt Install the rocket_db_pools crate to manage MongoDB connections within Rocket. ```shell cargo add -F mongodb rocket_db_pools ``` -------------------------------- ### Configure Default Authentication Source: https://context7.com/mongodb/docs-rust/llms.txt Sets up default authentication using SCRAM-SHA-256 or SCRAM-SHA-1 with provided username and password. ```rust use mongodb::{bson::doc, options::{AuthMechanism, ClientOptions, Credential}, Client}; #[tokio::main] async fn main() -> mongodb::error::Result<()> { // Default authentication (SCRAM-SHA-256 or SCRAM-SHA-1) let uri = "mongodb://localhost:27017"; let mut client_options = ClientOptions::parse(uri).await?; let default_cred = Credential::builder() .username("db_username".to_string()) .password("db_password".to_string()) .source("admin".to_string()) .build(); client_options.credential = Some(default_cred); let client = Client::with_options(client_options)?; Ok(()) } ``` -------------------------------- ### Access Data from a Cursor Iteratively (Sync) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Iterate over results from a query using a cursor. This example uses the synchronous runtime. ```rust let mut cursor = collection.find(doc! { "status": "pending" })?; while let Some(doc) = cursor.next()? { println!("{:?}", doc?); } ``` -------------------------------- ### Access Data from a Cursor Iteratively (Async) Source: https://github.com/mongodb/docs-rust/blob/master/source/quick-reference.txt Iterate over results from a query using a cursor. This example uses the asynchronous runtime. ```rust let mut cursor = collection.find(doc! { "status": "pending" }).await?; while let Some(doc) = cursor.next().await { println!("{:?}", doc?); } ``` -------------------------------- ### Run Aggregation Pipelines in Rust Source: https://context7.com/mongodb/docs-rust/llms.txt Demonstrates how to execute aggregation pipelines for data transformation and analysis, including grouping, calculating statistics, and sorting results. Requires `bson` and `mongodb` crates. ```rust use bson::{doc, DateTime, Document}; use futures::stream::TryStreamExt; use mongodb::{Client, Collection}; #[tokio::main] async fn main() -> mongodb::error::Result<()> { let client = Client::with_uri_str("mongodb://localhost:27017").await?; let my_coll: Collection = client.database("db").collection("site_users"); // Aggregation: Group by genre and calculate age statistics let age_pipeline = vec![ doc! { "$unwind": doc! { "path": "$genre_interests" } }, doc! { "$group": doc! { "_id": "$genre_interests", "avg_age": doc! { "$avg": "$age" }, "min_age": doc! { "$min": "$age" }, "max_age": doc! { "$max": "$age" } } }, ]; let mut results = my_coll.aggregate(age_pipeline).await?; while let Some(result) = results.try_next().await? { println!("* {:?}", result); } // Aggregation: Count users by month of last activity let last_active_pipeline = vec![ doc! { "$project": { "month_last_active": doc! { "$month": "$last_active" } } }, doc! { "$group": doc! { "_id": doc! { "month_last_active": "$month_last_active" }, "number": doc! { "$sum": 1 } } }, doc! { "$sort": { "_id.month_last_active": 1 } }, ]; let mut results = my_coll.aggregate(last_active_pipeline).await?; while let Some(result) = results.try_next().await? { println!("* {:?}", result); } // Aggregation: Find top 3 most popular genres let popularity_pipeline = vec![ doc! { "$unwind": "$genre_interests" }, doc! { "$group": doc! { "_id": "$genre_interests", "number": doc! { "$sum": 1 } } }, doc! { "$sort": doc! { "number": -1 } }, doc! { "$limit": 3 }, ]; let mut results = my_coll.aggregate(popularity_pipeline).await?; while let Some(result) = results.try_next().await? { println!("* {:?}", result); } Ok(()) } ``` -------------------------------- ### Access Databases and Collections Source: https://context7.com/mongodb/docs-rust/llms.txt Demonstrates accessing databases, listing collections, creating new collections, and dropping collections and databases. Collections can be typed with custom structs for automatic serialization/deserialization. ```rust use bson::Document; use mongodb::{bson::doc, options::{CollectionOptions, WriteConcern}, Client, Collection}; #[tokio::main] async fn main() -> mongodb::error::Result<()> { let client = Client::with_uri_str("mongodb://localhost:27017").await?; // List all database names let db_list = client.list_database_names().await?; println!("Databases: {:?}", db_list); // Access a database let db = client.database("test_db"); // List all collection names let coll_list = db.list_collection_names().await?; println!("Collections: {:?}", coll_list); // Create a new collection db.create_collection("coll_abc").await?; // Access a collection with write concern options let wc = WriteConcern::builder().journal(true).build(); let coll_opts = CollectionOptions::builder().write_concern(wc).build(); let my_coll: Collection = db.collection_with_options("coll_xyz", coll_opts); // Drop a collection my_coll.drop().await?; // Drop a database db.drop().await?; Ok(()) } ``` -------------------------------- ### Sample Book Data Source: https://github.com/mongodb/docs-rust/blob/master/source/fundamentals/crud/read-operations/sort.txt This snippet displays sample book documents, each with an ID, name, author, and length. It is presented in a console output format. ```console Book { "_id": 1, "name": "The Brothers Karamazov", "author": Dostoevsky, "length": 824 } Book { "_id": 3, "name": "Les Miserables", "author": Hugo, "length": 1462 } Book { "_id": 2, "name": "Atlas Shrugged", "author": Rand, "length": 1088 } Book { "_id": 4, "name": "A Dance with Dragons", "author": Martin, "length": 1104 } ```