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
TLS Options
For more information on TLS options, see the Enable TLS on a Connection guide.
Timeout Options
Compression Options
For more information on compression, see the Compress Network Traffic guide.
Connection Pool Options
To learn more about connection pools, see the Connection Pools guide.
Write Concern Options
Read Concern Options
Read Preference Options
Authentication Options
Server Selection Options
Retry Options
Miscellaneous Options
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: