Docs Menu
Docs Home
/ / /
Go Driver
/

Choose a Connection Target

In this guide, you can learn how to use a connection string and a MongoClient object to connect to different types of MongoDB deployments by using the Go driver.

Tip

To see how to create and configure your MongoClient object, see the Create a Mongo Client page.

To connect to a MongoDB deployment on Atlas, include the following elements in your connection string:

  • URL of your Atlas cluster

  • MongoDB username

  • MongoDB password

Then, pass your connection string to the MongoClient constructor.

When you connect to Atlas, we recommend using the Stable API client option to avoid breaking changes when Atlas upgrades to a new version of MongoDB Server. To learn more about the Stable API feature, see the Stable API guide.

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"
"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/")
}
// 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(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!")
}

Important

New Serverless instances can no longer be created, and as of May 5 2025, all existing Serverless instances have been migrated. The All Clusters page in the Atlas UI shows which tiers your instances are migrated to based on usage. See the Manage Serverless Instances page to learn more about how to manually handle existing Serverless instances.

If you must run a MongoDB server on your local machine for development purposes, complete the following steps:

  1. Download the Community or Enterprise version of MongoDB Server.

  2. Install and configure MongoDB Server.

  3. 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.

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 connection string, 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, you must provide the full list of hosts to ensure connectivity when the specified host is unavailable.

To force operations on the host designated in the connection string, specify the directConnection option. Direct connections exhibit the following behavior:

  • They don't support SRV strings.

  • They fail on writes when the specified host is not the primary.

  • They require you to specify a secondary node with secondary read preference when the specified host isn't the primary node.

Note

Replica Set in Docker

When a replica set runs in Docker, it might expose only one MongoDB endpoint. In this case, the replica set is not discoverable. Specifying directConnection=false in your connection URI, or leaving this option unset, can prevent your application from connecting to it.

In a test or development environment, you can connect to the replica set by specifying directConnection=true. In a production environment, we recommend configuring the cluster to make each MongoDB instance accessible outside of the Docker virtual network.

To learn more about connecting to different MongoDB instances with a MongoClient, see the following API Documentation:

Back

Create a MongoClient

On this page