specify-connection-options

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: connection-string, client-options -->

Specify Connection Options

Overview

This page describes the connection options available in the Go driver and explains how to apply them to your MongoDB connection.

How to Specify Connection Options

The following sections describe how you can specify connection options by using a connection string or a ClientOptions struct.

Use the Connection String

You can specify connection options in a connection string by passing a ClientOptions struct to the Connect() method. In the connection string, you can include connection options in the string as <name>=<value> pairs. In the following example, the connection string contains the connectTimeoutMS option with a value of 60000 milliseconds and the tls option with a value of true:

const uri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Use the ClientOptions Struct

You can also chain connection options to the ClientOptions struct to configure connection settings. Configuring the connection this way makes it easier to change settings at runtime, helps you catch errors during compilation, and provides more configuration options than the connection string.

The following code example sets the Timeout option to 60 seconds and enables TLS by passing an empty tls.Config struct to the SetTLSConfig() method:

opts := options.Client().
    SetConnectTimeout(60 * time.Second).
    SetTLSConfig(&tls.Config{})

client, _ := mongo.Connect(opts)

Replica Set Options

Connection String

Direct Connection

Specifies whether to force dispatch all operations to the host. If you specify this option, the driver doesn't accept the SRV connection format. You must use the standard connection URI format instead. To learn more about the SRV connection and the standard connection formats, see the [Connection Strings](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri guide in the MongoDB Server manual.

This property must be set to false if you specify more than one host name.

Data Type: bool

Default Value: false

Example:

const uri = "mongodb://localhost:27017/?directConnection=true"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Replica Set

The name of the replica set to connect to.

Data Type: string

Default Value: nil

Example:

const uri = "mongodb://localhost:27017/?replicaSet=yourReplicaSet"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

TLS Options

Connection String

Enable TLS

Specifies whether to require TLS for connections to the server. If you use a scheme of “mongodb+srv” or specify other TLS options, this option defaults to true. Otherwise, it defaults to false.

Data Type: bool

Default Value: nil

Example:

const uri = "mongodb://localhost:27017/?tls=true"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Disable Certificate Revocation

The tlsDisableCertificateRevocationCheck option disables certificate revocation checking for TLS connections. When you set this option to true, the driver does not verify the revocation status of certificates but still validates the certificate chain and hostname. Setting this option implicitly enables TLS, even when you set it to false. Do not combine this option with tlsInsecure or tlsDisableOCSPEndpointCheck.

Data Type: bool

Default Value: false

Example:

uri := os.Getenv("MONGODB_URI")
if uri == "" {
    log.Fatal("Set your 'MONGODB_URI' environment variable")
}

// Use an ampersand instead of a question mark if the connection string
// already contains query options.
separator := "?"
if strings.Contains(uri, "?") {
    separator = "&"
}

uriOptions := options.Client().
    ApplyURI(uri + separator + "tlsDisableCertificateRevocationCheck=true")

For more information on TLS options, see the [Enable TLS on a Connection](https://www.mongodb.com/docs/drivers/go/current/security/tls.md#std-label-golang-tls guide.

Timeout Options

Connection String

Connect Timeout

The length of time the driver tries to establish a single TCP socket connection to the server before timing out.

Data Type: non-negative int

Default Value: 30000 milliseconds

Example:

const uri = "mongodb://localhost:27017/?connectTimeoutMS=60000"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Timeout

The timeoutMS option specifies the amount of time that a single operation run on the client can execute before returning an error.

Data Type: non-negative int

Default Value: nil

Example:

const uri = "mongodb://localhost:27017/?timeoutMS=30000"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Compression Options

Connection String

Compressors

The preferred compression types, in order, for wire-protocol messages sent to or received from the server. You can enable “snappy”, “zlib”, and “zstd” as optional build time dependencies. The driver uses the first of these compression types that the server supports.

Data Type: string (values separated by commas)

Default Value: nil

Example:

const uri = "mongodb://localhost:27017/?compressors=zlib,snappy"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Zlib Compression Level

The zlibCompressionLevel option sets the compression level for zlib to use. This option is ignored if zlib is not specified as a compressor through ApplyURI or SetCompressors. This option accepts an integer value between -1 and 9:

  • -1: (Default). zlib uses its default compression level (usually 6).

  • 0: No compression.

  • 1: Fastest speed but lowest compression.

  • 9: Best compression but slowest speed.

Data Type: int

Default Value: -1

Example:

const uri = "mongodb://localhost:27017/?compressors=zlib&zlibCompressionLevel=6"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Zstandard Compression Level

The zstdCompressionLevel option sets the compression level for zstd to use. This option is ignored if zstd is not specified as a compressor through ApplyURI or SetCompressors. This option accepts integer values between 1 and 20:

  • 1: Fastest speed but lowest compression.

  • 20: Best compression but slowest speed.

Data Type: int

Default Value: 6

Example:

const uri = "mongodb://localhost:27017/?compressors=zstd&zstdCompressionLevel=6"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

For more information on compression, see the [Compress Network Traffic](https://www.mongodb.com/docs/drivers/go/current/connect/connection-options/network-compression.md#std-label-golang-network-compression guide.

Connection Pool Options

Connection String

Max Pool Size

The greatest number of clients or connections the driver can create in its connection pool. This count includes connections in use.

Data Type: non-negative int

Default Value: 100

Example:

const uri = "mongodb://localhost:27017/?maxPoolSize=150"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Min Pool Size

The number of connections the driver creates and keeps in the connection pool even when no operations are occurring. This count includes connections in use.

Data Type: non-negative int

Default Value: 0

Example:

const uri = "mongodb://localhost:27017/?minPoolSize=3"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Max Connection Idle Time

The length of time a connection can be idle before the driver closes it.

Data Type: non-negative int

Default Value: 0

Example:

const uri = "mongodb://localhost:27017/?maxIdleTimeMS=8000"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Max Connecting

The maxConnecting option sets the maximum number of connections a connection pool may establish simultaneously.

Data Type: non-negative int

Default Value: 2

Example:

const uri = "mongodb://localhost:27017/?maxConnecting=3"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

To learn more about connection pools, see the [Connection Pools](https://www.mongodb.com/docs/drivers/go/current/connect/connection-options/connection-pools.md#std-label-golang-connection-pools guide.

Write Concern Options

Connection String

Write Concern

The w component of the write concern, which requests acknowledgment that the write operation has propagated to a specified number of MongoDB instances. The default value is “majority” or 1, depending on the number of arbiters and voting nodes. To learn more about the w option, see [Write Concern](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-wc-w in the MongoDB Server manual.

Data Type: int or string

Default Value: 1 or “majority”

Example:

const uri = "mongodb://localhost:27017/?w=2"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Read Concern Options

Connection String

Read Concern

The client's read concern level. For more information, see the [Read Concern](https://www.mongodb.com/docs/manual/reference/read-concern.md#std-label-read-concern reference in the MongoDB Server manual.

Data Type: string

Default Value: local

Example:

const uri = "mongodb://localhost:27017/?readConcernLevel=majority"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Read Preference Options

Connection String

Read Preference

The client's default read-preference settings. See [Read Preference](https://www.mongodb.com/docs/manual/core/read-preference.md#std-label-read-preference in the MongoDB Server manual for more information.

Data Type: string

Default Value: primary

Example:

const uri = "mongodb://localhost:27017/?readPreference=primaryPreferred"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Authentication Options

Connection String

Authentication Mechanism

The mechanism that the driver uses to authenticate to MongoDB Server. If you don't specify an authentication mechanism, the driver uses either SCRAM-SHA-1 or SCRAM-SHA-256, depending on the server version.

To learn more about available authentication mechanisms, see the [Authentication Mechanism](https://www.mongodb.com/docs/drivers/go/current/security/authentication.md#std-label-golang-authentication guides.

Data Type: string

Default Value: empty (no authentication), or SCRAM-SHA-256 once authentication is enabled

Example:

const uri = "mongodb://user:password@localhost:27017/?authMechanism=PLAIN&authSource=admin"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Server Selection Options

Connection String

Server Selection Timeout

The length of time the driver tries to select a server before timing out.

Data Type: non-negative int

Default Value: 30000 milliseconds

Example:

const uri = "mongodb://localhost:27017/?serverSelectionTimeoutMS=40000"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Local Threshold

The latency window for server eligibility. If a server's round trip takes longer than the fastest server's round-trip time plus this value, the server isn't eligible for selection.

Data Type: non-negative int

Default Value: 15 milliseconds

Example:

const uri = "mongodb://localhost:27017/?localThresholdMS=20000"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Retry Options

Connection String

Retry Reads

Enables retryable reads.

Data Type: bool

Default Value: true

Example:

const uri = "mongodb://localhost:27017/?retryReads=false"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Retry Writes

Enables retryable writes.

Data Type: bool

Default Value: true

Example:

const uri = "mongodb://localhost:27017/?retryWrites=false"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Max Adaptive Retries

The maxAdaptiveRetries option sets the maximum number of times the driver should retry operations that fail with a server-side overload error.

Data Type: non-negative int

Default Value: 2

Example:

const uri = "mongodb://localhost:27017/?maxAdaptiveRetries=3"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Miscellaneous Options

Connection String

Application Name

The app name the driver passes to the server in the client metadata as part of the connection handshake. The server prints this value to the MongoDB logs once it establishes the connection. The value is also recorded in the slow query logs and profile collections.

Data Type: string

Default Value: nil

Example:

const uri = "mongodb://localhost:27017/?appName=yourAppName"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Load Balanced

Specifies whether the driver is connecting to a load balancer. You can set this property to true only if all the following conditions are met:

  • You specify just one host name

  • You're not connecting to a replica set

  • You're not using the SrvMaxHosts property

  • You're not using the DirectConnection property

Data Type: bool

Default Value: false

Example:

const uri = "mongodb://localhost:27017/?loadBalanced=true"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

SRV Max Hosts

The greatest number of SRV results to randomly select when initially populating the seedlist or, during SRV polling, adding new hosts to the topology.

You can use this property only if the connection-string scheme is set to ConnectionStringScheme.MongoDBPlusSrv. You cannot use it when connecting to a replica set.

Data Type: non-negative int

Default Value: 0

Example:

opts := options.Client().
    SetSRVMaxHosts(5)

client, _ := mongo.Connect(opts)

SRV Service Name

The service name of the SRV resource records that the driver retrieves to construct your seedlist. The driver uses the service name to create the SRV URI, which matches the following format:

_{srvServiceName}._tcp.{hostname}.{domainname}

This property overrides the default service name for SRV lookup in discovery and polling. The default value is “mongodb”.

You can use this property only if the connection-string scheme is set to ConnectionStringScheme.MongoDBPlusSrv. You cannot use it when connecting to a replica set.

Data Type: string

Default Value: mongodb

Example:

const uri = "mongodb+srv://localhost/?srvServiceName=yourServiceName"
client, _ := mongo.Connect(options.Client().ApplyURI(uri))

Additional Information

To learn more about the options that you can specify in a connection string, see [Connection String Options](https://www.mongodb.com/docs/manual/reference/connection-string-options.md#std-label-connections-connection-options in the MongoDB Server manual.

For more information about the types used on this page, see the following API documentation:

  • [Client](https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo#Client

  • [ClientOptions](https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo/options#ClientOptions