Create a MongoClient
Overview
In this guide, you can learn how to connect to a MongoDB Atlas deployment, a MongoDB instance, or a replica set using the Go driver.
To connect to a MongoDB deployment, you need the following two things:
Connection URI, also known as a connection string, which tells the Go driver which MongoDB deployment to connect to.
MongoClient object, which creates the connection to and performs operations on the MongoDB deployment.
You can use options.Client()
to customize the way the Go driver
behaves while connected to MongoDB.
Connection URI
A standard connection string includes the following components:
Component | Description |
---|---|
| Required. A prefix that identifies this as a string in the standard connection format. |
| Optional. Authentication credentials. If you include these, the client
authenticates the user against the database specified in |
| Required. The host and optional port number where MongoDB is running. If you don't
include the port number, the driver uses the default port, |
| Optional. The authentication database to use if the
connection string includes |
| Optional. A query string that specifies connection-specific
options as |
Tip
To retrieve a connection string for an Atlas deployment, follow the Quick Start guide.
For more information about creating a connection string, see Connection Strings in the MongoDB Server documentation.
Create a Client to Connect to MongoDB Atlas
To connect to MongoDB, you must create a client. A client manages your connections and runs database commands.
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.
Tip
Reuse Your Client with Connection Pools
We recommend that you reuse your client across sessions and operations by
using a connection pool. 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 Connection Pools guide.
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.
Example
The following code shows how you can create a client that uses an Atlas connection string and the Stable API version, connects to MongoDB, and verifies that the connection is successful:
// Connects to MongoDB and sets a Stable API version package main import ( "context" "fmt" "log" "os" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) func main() { var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/") } // Uses the SetServerAPIOptions() method to set the Stable API version to 1 serverAPI := options.ServerAPI(options.ServerAPIVersion1) // Defines the options for the MongoDB client opts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPI) // Creates a new client and connects to the server client, err := mongo.Connect(opts) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() // Sends 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!") }
Additional Resources
For more information about the concepts in this guide, see the following documentation:
Connection Strings in the Server manual
Connection String Options in the Server manual
Driver Connection guide in the Atlas documentation and select Go from the language dropdown
API Documentation
To learn more about the methods and types discussed in this guide, see the following API Documentation: