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
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 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))
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 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:
opts := options.Client(). SetDirect(true) client, _ := mongo.Connect(opts)
Replica Set
The name of the replica set to connect to.
Data Type: string
Default Value: nil
Example:
opts := options.Client(). SetReplicaSet("yourReplicaSet") client, _ := mongo.Connect(opts)
TLS Options
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))
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: tls.Config
Default Value: false
Example:
opts := options.Client(). SetTLSConfig(&tls.Config{}) client, _ := mongo.Connect(opts)
For more information on TLS options, see the Enable TLS on a Connection guide.
Timeout Options
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 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))
Connect Timeout
The length of time the driver tries to establish a single TCP socket connection to the server before timing out.
Data Type: time.Duration
Default Value: 30 seconds
Example:
opts := options.Client(). SetConnectTimeout(60 * time.Second) client, _ := mongo.Connect(opts)
Timeout
The amount of time that a single operation run on the client can execute before returning an error.
Data Type: time.Duration
Default Value: nil
Example:
opts := options.Client(). SetTimeout(30 * time.Second) client, _ := mongo.Connect(opts)
Compression Options
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 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).zlibuses its default compression level (usually6).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 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))
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
Default Value: nil
Example:
opts := options.Client(). SetCompressors([]string{"zlib", "snappy"}) client, _ := mongo.Connect(opts)
Zlib Compression Level
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).
zlibuses its default compression level (usually6).0: No compression.
1: Fastest speed but lowest compression.
9: Best compression but slowest speed.
Data Type: int
Default Value: -1
Example:
opts := options.Client(). SetCompressors([]string{"zlib"}). SetZlibLevel(6) client, _ := mongo.Connect(opts)
Zstandard Compression Level
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:
Data Type: int
Default Value: 6
Example:
opts := options.Client(). SetCompressors([]string{"zstd"}). SetZstdLevel(8) client, _ := mongo.Connect(opts)
For more information on compression, see the Network Compression guide.
Connection Pool Options
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 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))
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 uint64
Default Value: 100
Example:
opts := options.Client(). SetMaxPoolSize(150) client, _ := mongo.Connect(opts)
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 uint64
Default Value: 0
Example:
opts := options.Client(). SetMinPoolSize(3) client, _ := mongo.Connect(opts)
Max Connection Idle Time
The length of time a connection can be idle before the driver closes it.
Data Type: time.Duration
Default Value: 0
Example:
opts := options.Client(). SetMaxConnIdleTime(8 * time.Second) client, _ := mongo.Connect(opts)
Max Connecting
The maximum number of connections a connection pool may establish simultaneously.
Data Type: non-negative uint64
Default Value: 2
Example:
opts := options.Client(). SetMaxConnecting(3) client, _ := mongo.Connect(opts)
To learn more about connection pools, see the Connection Pools guide.
Write Concern Options
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 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))
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 in the MongoDB Server manual.
Data Type: writeconcern.WriteConcern
Default Value: 1 or "majority"
Example:
wc := &writeconcern.WriteConcern{ W: 2, } opts := options.Client().SetWriteConcern(wc) client, _ := mongo.Connect(opts)
Read Concern Options
Read Concern
The client's read concern level. For more information, see the 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 Concern
The client's read concern level. For more information, see the Read Concern reference in the MongoDB Server manual.
Data Type: readconcern.ReadConcern
Default Value: nil
Example:
opts := options.Client(). SetReadConcern(readconcern.Majority()) client, _ := mongo.Connect(opts)
Read Preference Options
Read Preference
The client's default read-preference settings. See 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))
Read Preference
The client's default read-preference settings. See Read Preference in the MongoDB Server manual for more information.
Data Type: readpref.ReadPref
Default Value: readpref.Primary()
Example:
opts := options.Client(). SetReadPreference(readpref.PrimaryPreferred()) client, _ := mongo.Connect(opts)
Authentication Options
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 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))
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 guides.
Data Type: Credential
Default Value: empty (no authentication), or SCRAM-SHA-256 once authentication is enabled
Example:
credential := options.Credential{ AuthMechanism: "PLAIN", AuthSource: "admin", Username: "user", Password: "password", } opts := options.Client().SetAuth(credential) client, _ := mongo.Connect(opts)
Server Selection Options
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))
Server Selection Timeout
The length of time the driver tries to select a server before timing out.
Data Type: time.Duration
Default Value: 30 seconds
Example:
opts := options.Client(). SetServerSelectionTimeout(40 * time.Second) client, _ := mongo.Connect(opts)
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: time.Duration
Default Value: 15 milliseconds
Example:
opts := options.Client(). SetLocalThreshold(20 * time.Millisecond) client, _ := mongo.Connect(opts)
Retry Options
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 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))
Retry Reads
Enables retryable reads.
Data Type: bool
Default Value: true
Example:
opts := options.Client(). SetRetryReads(false) client, _ := mongo.Connect(opts)
Retry Writes
Enables retryable writes.
Data Type: bool
Default Value: true
Example:
opts := options.Client(). SetRetryWrites(false) client, _ := mongo.Connect(opts)
Max Adaptive Retries
The maximum number of times the driver should retry operations that fail with a server-side overload error.
Data Type: non-negative uint
Default Value: 2
Example:
const uri = "mongodb://localhost:27017/?maxAdaptiveRetries=3" client, _ := mongo.Connect(options.Client().ApplyURI(uri))
Miscellaneous Options
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
SrvMaxHostspropertyYou're not using the
DirectConnectionproperty
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))
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:
opts := options.Client(). SetAppName("yourAppName") client, _ := mongo.Connect(opts)
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
SrvMaxHostspropertyYou're not using the
DirectConnectionproperty
Data Type: bool
Default Value: false
Example:
opts := options.Client(). SetLoadBalanced(true) client, _ := mongo.Connect(opts)
Server API
Configure the API version sent to the server when running commands. For more information on the Server API, see the Stable API guide.
Data Type: ServerAPIOptions
Default Value: nil
Example:
opts := options.Client(). SetServerAPIOptions(options.ServerAPI(options.ServerAPIVersion1)) client, _ := mongo.Connect(opts)
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:
opts := options.Client(). SetSRVServiceName("yourServiceName") client, _ := mongo.Connect(opts)
Additional Information
To learn more about the options that you can specify in a connection string, see Connection String Options in the MongoDB Server manual.
For more information about the types used on this page, see the following API documentation: