Overview
In this guide, you can learn how to use a connection string and a Client instance
to connect to different types of MongoDB deployments.
Connect to an Atlas Deployment
To connect to a MongoDB deployment on Atlas, include the following elements in your connection string:
URL of your Atlas cluster
MongoDB username
MongoDB password
Then, construct a Client instance with your connection string.
Tip
Follow the Atlas driver connection guide to retrieve your connection string.
When you connect to Atlas, we recommend using the Stable API client option to avoid breaking changes when Atlas upgrades to a new version of the MongoDB Server. To learn more about the Stable API feature, see the Stable API guide.
The following code shows how you can create a client that uses an Atlas connection string and the Stable API version, connect to MongoDB, and verify that the connection is successful. Select from the Asynchronous API or Synchronous API tabs below for corresponding connection code samples.
Tip
To learn more about asynchronous and synchronous runtimes, see the Asynchronous and Synchronous APIs guide.
use mongodb::{ bson::doc, options::{ ClientOptions, ServerApi, ServerApiVersion }, Client }; async fn main() -> mongodb::error::Result<()> { // Replace the placeholder with your Atlas connection string let uri = "<connection string>"; let mut client_options = ClientOptions::parse(uri).await?; // Set the server_api field of the client_options object 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(()) }
use mongodb::{ bson::doc, options::{ ClientOptions, ServerApi, ServerApiVersion }, sync::Client }; fn main() -> mongodb::error::Result<()> { // Replace the placeholder with your Atlas connection string let uri = "<connection string>"; let mut client_options = ClientOptions::parse(uri).run()?; // Set the server_api field of the client_options object 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 }).run()?; println!("Pinged your deployment. You successfully connected to MongoDB!"); Ok(()) }
Other Ways to Connect to MongoDB
If you must connect to a single MongoDB server instance or replica set that is not hosted on Atlas, see the following sections to find out how to connect.
Connect to a MongoDB Server on Your Local Machine
If you must run the MongoDB Server on your local machine for development purposes, you must complete the following:
Follow the Install MongoDB tutorial to install the MongoDB Server on your machine. Select the appropriate installation tutorial for your machine and operating system.
After you complete the installation, start the server.
Important
Always secure your server from malicious attacks. See the Security Checklist for a list of security recommendations.
After you successfully start the MongoDB Server, connect to your local instance by performing the following steps:
Replace the connection string stored in the
urivariable in the preceding example with the connection string for your local MongoDB instance.If your MongoDB Server is running locally, you can use the following connection string to connect to MongoDB:
mongodb://localhost:<port> In this connection string,
<port>is the port number you configured your server to listen for incoming connections.Run the connection code. If the code executes successfully, you should see the following output in your console:
Pinged your deployment. You successfully connected to MongoDB!
Tip
To learn more about connection strings and custom formats, see Connection Strings in the Server manual.
Connect to a Replica Set
A MongoDB replica set deployment is a group of connected instances, or nodes, where the nodes store the same set of data. This configuration of instances provides data redundancy and high data availability.
To connect to a replica set deployment, specify the hostname and port numbers
of each instance, separated by commas, and the replica set name as the value
of the replicaSet parameter in the connection string.
In the following example, the hostnames are host1, host2, and
host3, and the port numbers are all 27017. The replica set name
is myRS. The following code shows the connection URI for the replica
set with these specifications:
mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRS
When connecting to a replica set, the driver takes the following actions by default:
Discovers all replica set members when given the address of any one member.
Sends operations to the appropriate member, such as instructions to write against the primary node. To learn more about the replica set primary, see Replica Set Primary in the Server manual.
Tip
You are only required to specify one host to connect to a replica set. However, to ensure connectivity when the specified host is unavailable, provide the full list of hosts.
Direct Connection
To force operations on the host designated in the connection URI,
specify the directConnection option. Direct connections display the
following behavior:
They don't support SRV strings.
They fail on writes when the specified host is not the primary.
They require you to specify a secondary read preference when the specified host isn't the primary member. To learn more about these replica set members, see Replica Set Secondary Members in the Server manual.
Note
Replica Set in Docker
When a replica set runs in Docker, it might expose only one MongoDB endpoint.
In this case, the replica set is not discoverable. Specifying directConnection=false in your connection URI,
or leaving this option unset, can prevent your application from connecting to it.
In a test or development environment, you can connect to the replica set by specifying
directConnection=true. In a production environment, we
recommend configuring the cluster to make each MongoDB instance accessible outside of
the Docker virtual network.
Connect with DNS Service Discovery
To use DNS service discovery to look up the DNS SRV record of the service you're connecting to, specify the SRV connection format in your connection string. If you specify this format, the Rust driver automatically rescans for new hosts. Your deployment can add hosts to its topology without requiring changes in your client configuration.
The following code shows a connection string that uses the SRV connection format:
let uri = "mongodb+srv://<hostname>/";
To learn more about the SRV connection format, see the SRV Connection Format entry in the MongoDB Server manual.
API Documentation
To learn more about creating a Client instance with the Rust driver,
see the API documentation for Client.