Connecting to the Database

Connection String

Connecting to a MongoDB database requires using a connection string, a URI of the form:

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

At its simplest this can just specify the host and port, e.g.

mongodb://mongodb0.example.com:27017

For the full range of options supported by the Rust driver, see the documentation for the ClientOptions::parse method. That method will return a ClientOptions struct, allowing for directly querying or setting any of the options supported by the Rust driver:


#![allow(unused)]
fn main() {
extern crate mongodb;
use mongodb::options::ClientOptions;
async fn run() -> mongodb::error::Result<()> {
let mut options = ClientOptions::parse("mongodb://mongodb0.example.com:27017").await?;
options.app_name = Some("My App".to_string());
Ok(())
}
}

Creating a Client

The Client struct is the main entry point for the driver. You can create one from a ClientOptions struct:


#![allow(unused)]
fn main() {
extern crate mongodb;
use mongodb::{Client, options::ClientOptions};
async fn run() -> mongodb::error::Result<()> {
let options = ClientOptions::parse("mongodb://mongodb0.example.com:27017").await?;
let client = Client::with_options(options)?;
Ok(())
}
}

As a convenience, if you don't need to modify the ClientOptions before creating the Client, you can directly create one from the connection string:


#![allow(unused)]
fn main() {
extern crate mongodb;
use mongodb::Client;
async fn run() -> mongodb::error::Result<()> {
let client = Client::with_uri_str("mongodb://mongodb0.example.com:27017").await?;
Ok(())
}
}

Client uses std::sync::Arc internally, so it can safely be shared across threads or async tasks. For example:


#![allow(unused)]
fn main() {
extern crate mongodb;
extern crate tokio;
use mongodb::{bson::Document, Client, error::Result};
use tokio::task;

async fn start_workers() -> Result<()> {
let client = Client::with_uri_str("mongodb://example.com").await?;

for i in 0..5 {
    let client_ref = client.clone();

    task::spawn(async move {
        let collection = client_ref.database("items").collection::<Document>(&format!("coll{}", i));

        // Do something with the collection
    });
}

Ok(())
}
}

Client Performance

While cloning a Client is very lightweight, creating a new one is an expensive operation. For most use cases, it is highly recommended to create a single Client and persist it for the lifetime of your application. For more information, see the Performance chapter.