Connection Guide
Overview
In this guide, you can learn how to connect to a MongoDB instance or replica set deployment by using the Go driver.
You can use the Go driver to connect to deployments hosted in the following environments:
MongoDB Atlas: the fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: the subscription-based, self-managed version of MongoDB
MongoDB Community: the source-available, free-to-use, and self-managed version of MongoDB
Connection URI
A connection URI, also known as a connection string, tells the driver how to connect to MongoDB and how to behave while connected.
Parts of a Connection URI
The following example explains each part of a sample connection URI:
In this example, we use mongodb
for the protocol, which specifies the
Standard Connection String Format.
You can also use the DNS Seed List Connection Format if you
want more flexibility of deployment and the ability to change the
servers in rotation without reconfiguring clients.
The next part of the connection string contains your database username and, if
you are using password-based authentication, your password. Replace the value of
user
with your database username and pass
with your password. If you are using an
authentication mechanism that does not require a username and password, omit
this part of the connection URI.
The next part of the connection string specifies the hostname or IP address and
port of your MongoDB instance. In the preceding example, we use sample.host
as the hostname and 27017
as the port. Replace these values to point to
your MongoDB instance.
The last part of the connection string specifies connection and authentication
options. In the example, we set two connection options:
maxPoolSize=20
and w=majority
. To learn more about connection
options, read the Connection Options section of this guide.
Connection Example
To connect to MongoDB, you must create a client. A client manages your connections and runs database commands.
Tip
Reuse Your Client
We recommend that you reuse your client across sessions and operations.
You can use the same Client
instance to perform multiple tasks, instead of
creating a new one each time. The Client
type is safe for
concurrent use by multiple goroutines. To learn more about
how connection pools work in the driver, see the FAQ page.
You can create a client that uses your connection string and other
client options by passing a ClientOptions
object to the Connect()
method.
To specify your connection URI, pass it to the ApplyURI()
method, which returns a new ClientOptions
instance. To set any other
options, call the relevant helper method from the options
package.
To learn more about connection options, see the Connection Options section. To learn more about creating a client, see the API documentation for Client and Connect().
You can set the Stable API version as an option to avoid breaking changes when you upgrade to a new server version. To learn more about the Stable API feature, see the Stable API page.
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:
// Connects to MongoDB and sets a Stable API version package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) // Replace the placeholder with your Atlas connection string const uri = "<connection string>" func main() { // Use the SetServerAPIOptions() method to set the Stable API version to 1 serverAPI := options.ServerAPI(options.ServerAPIVersion1) opts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPI) // Create a new client and connect to the server client, err := mongo.Connect(context.TODO(), opts) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() // Send a ping to confirm a successful connection var result bson.M if err := client.Database("admin").RunCommand(context.TODO(), bson.D{{"ping", 1}}).Decode(&result); err != nil { panic(err) } fmt.Println("Pinged your deployment. You successfully connected to MongoDB!") }
Tip
Follow the Quick Start guide to retrieve your Atlas connection string.
Note
To learn about connecting to Atlas Serverless, see the Serverless Instance Limitations page to identify the minimum driver version required.
Other Ways to Connect to MongoDB
If you are connecting 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 a MongoDB server on your local machine for development purposes, complete the following steps:
Download the Community or Enterprise version of MongoDB Server.
Install and configure MongoDB Server.
Start the server.
Important
Always secure your MongoDB server from malicious attacks. See our Security Checklist for a list of security recommendations.
After you successfully start your MongoDB server, specify your connection string in your driver connection code.
If your MongoDB Server is running locally, you can use the connection string
"mongodb://localhost:<port>"
where <port>
is the port number you
configured your server to listen for incoming connections.
If you want to specify a different hostname or IP address, see our Server Manual entry on Connection Strings.
To test whether you can connect to your server, replace the connection string with your localhost connection string in the preceding code example.
Connect to a Replica Set
A MongoDB replica set deployment is a group of connected instances that store the same set of data. This configuration 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
.
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.
Dispatches operations to the appropriate member, such as instructions to write against the primary.
Tip
You can specify just one host to connect to a replica set. However, to ensure connectivity when the specified host is unavailable, you should 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:
Don't support SRV strings.
Fail on writes when the specified host is not the primary.
Require you to specify a secondary read preference when the specified host isn't the primary.
Connection Options
This section explains several common MongoDB connection and authentication options. You can pass the connection options as parameters of the connection URI to specify the behavior of the client.
Option Name | Type | Default Value | Description |
---|---|---|---|
timeoutMS | integer | null | Specifies the number of milliseconds that a single operation run on the
Client can take before returning a timeout error. Operations honor
this setting only if there is no deadline on the operation Context. |
connectTimeoutMS | integer | 30000 | Specifies the number of milliseconds to wait before timeout on a TCP
connection. |
maxPoolSize | integer | 100 | Specifies the maximum number of connections that a connection pool may
have at a given time. |
replicaSet | string | null | Specifies the replica set name for the cluster. All nodes in the
replica set must have the same replica set name, or the Client will not
consider them as part of the set. |
maxIdleTimeMS | integer | 0 | Specifies the maximum amount of time a connection can remain idle
in the connection pool before being removed and closed. The
default is 0 , meaning a connection can remain unused
indefinitely. |
minPoolSize | integer | 0 | Specifies the minimum number of connections that the driver maintains
in a single connection pool. |
socketTimeoutMS | integer | 0 | Specifies the number of milliseconds to wait for a socket read or
write to return before returning a network error. The 0
default value indicates that there is no timeout. |
serverSelectionTimeoutMS | integer | 30000 | Specifies the number of milliseconds to wait to find an available,
suitable server to execute an operation. |
heartbeatFrequencyMS | integer | 10000 | Specifies the number of milliseconds to wait between periodic
background server checks. |
tls | boolean | false | Specifies whether to establish a Transport Layer Security (TLS)
connection with the instance. This is automatically set to true
when using a DNS seedlist (SRV) in the connection string. You can
override this behavior by setting the value to false . |
w | string or integer | null | Specifies the write concern. To learn more about values, see the
server documentation on
Write Concern options. |
directConnection | boolean | false | Specifies whether to force dispatch all operations to the host
specified in the connection URI. |
For a full list of connection options, see the ClientOptions API documentation.
Single Timeout Setting
You can set a single Timeout
option on your Client
to govern the
amount of time that a single operation can take to execute using the
SetTimeout()
method or specifying the timeoutMS
option in your
connection URI string. Database
, Collection
,
Session
, ChangeStream
, and Bucket
instances elsewhere in
your code inherit the Timeout
option from Client
if you do not set a
Context for operations against the same entity.
If you pass a Context into an operation with a deadline, the driver uses
that Context deadline for the operation. If the context does not have a
deadline, the driver derives a new Context from the given Context using
the Timeout
option set on the Client
.
Note
Retries under Timeout Specification
With default settings, if you set a Timeout
option on your Client
and your operation requires a retry, the driver retries the operation
as many times as possible before the timeout expires. Once the timeout
expires, the driver returns a timeout error. Versions 1.1 and later
of the Go driver enable retryable reads and writes by default.
See the Server manual for more information about retryable
reads and retryable writes.
The following code shows how to set the Timeout
option on a Client
with the SetTimeout
option:
opts := options.Client().SetTimeout(5 * time.Second)
The following example shows how you can set a single timeout with the URI option and execute an operation that inherits this setting:
uri := "mongodb://user:pass@sample.host:27017/?timeoutMS=5000" client := mongo.Connect(context.TODO(), uri) coll := client.Database("<db>").Collection("<collection>") ... coll.InsertOne(context.Background(), doc)
Important
Legacy Timeout Options
SocketTimeout
, wTimeout
, MaxTime
, and MaxCommitTime
will be deprecated in an upcoming release. The driver ignores MaxTime
and
MaxCommitTime
if you set Timeout
. The driver still honors
SocketTimeout
and wTimeout
, but these settings may result in
undefined behavior. Consider using only the single timeout option instead.