Docs Menu
Docs Home
/ /

Connect to MongoDB

1

Open the file called main.rs in your rust_quickstart/src project directory. In this file, you can begin writing your application.

Copy and paste the following code into the main.rs file:

use mongodb::{
bson::{Document, doc},
Client,
Collection
};
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
// Replace the placeholder with your Atlas connection string
let uri = "<connection string>";
// Create a new client and connect to the server
let client = Client::with_uri_str(uri).await?;
// Get a handle on the movies collection
let database = client.database("sample_mflix");
let my_coll: Collection<Document> = database.collection("movies");
// Find a movie based on the title value
let my_movie = my_coll.find_one(doc! { "title": "The Perils of Pauline" }).await?;
// Print the document
println!("Found a movie:\n{:#?}", my_movie);
Ok(())
}
use mongodb::{
bson::{Document, doc},
sync::{Client, Collection}
};
fn main() -> mongodb::error::Result<()> {
// Replace the placeholder with your Atlas connection string
let uri = "<connection string>";
// Create a new client and connect to the server
let client = Client::with_uri_str(uri)?;
// Get a handle on the movies collection
let database = client.database("sample_mflix");
let my_coll: Collection<Document> = database.collection("movies");
// Find a movie based on the title value
let my_movie = my_coll
.find_one(doc! { "title": "The Perils of Pauline" })
.run()?;
// Print the document
println!("Found a movie:\n{:#?}", my_movie);
Ok(())
}
2

Replace the <connection string> placeholder with the connection string that you copied from the Create a Connection String step of this guide.

3

In your shell, run the following command to compile and run this application:

cargo run

The command line output contains details about the retrieved movie document:

Found a movie:
Some(
Document({
"_id": ObjectId(...),
"title": String(
"The Perils of Pauline",
),
"plot": String(
"Young Pauline is left a lot of money ...",
),
"runtime": Int32(
199,
),
"cast": Array([
String(
"Pearl White",
),
String(
"Crane Wilbur",
),
...
]),
}),
)

If you encounter an error or see no output, ensure that you specified the proper connection string in the main.rs file and that you loaded the sample data.

After you complete these steps, you have a working application that uses the driver to connect to your MongoDB deployment, runs a query on the sample data, and prints out the result.

Note

If you run into issues on this step, see the MongoDB Stack Overflow tag or the MongoDB Reddit community for general technical support, or see the Connection Troubleshooting guide.

Back

Create a Connection String