File tree Expand file tree Collapse file tree 2 files changed +40
-10
lines changed
includes/connection-snippets Expand file tree Collapse file tree 2 files changed +40
-10
lines changed Original file line number Diff line number Diff line change @@ -50,20 +50,12 @@ Connect to MongoDB Atlas
5050
5151.. include:: /includes/atlas-connect-blurb.rst
5252
53- .. code-block:: go
54-
55- import "go.mongodb.org/mongo-driver/mongo"
56-
57- ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
58- client, err := mongo.Connect(ctx, options.Client().ApplyURI(
59- "mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority"
60- ))
61- if err != nil { log.Fatal(err) }
53+ .. literalinclude:: /includes/connection-snippets/go-connection.go
54+ :language: go
6255
6356See `Usage <https://github.com/mongodb/mongo-go-driver#usage>`__
6457for more detail.
6558
66-
6759Compatibility
6860-------------
6961
Original file line number Diff line number Diff line change 1+ package main
2+
3+ import (
4+ "context"
5+ "fmt"
6+ "log"
7+ "time"
8+
9+ "go.mongodb.org/mongo-driver/mongo"
10+ "go.mongodb.org/mongo-driver/mongo/options"
11+ "go.mongodb.org/mongo-driver/mongo/readpref"
12+ )
13+
14+ func main () {
15+
16+ // Replace the uri string with your MongoDB deployment's connection string.
17+ uri := "mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority"
18+ ctx , cancel := context .WithTimeout (context .Background (), 10 * time .Second )
19+ defer cancel ()
20+
21+ client , err := mongo .Connect (ctx , options .Client ().ApplyURI (uri ))
22+ if err != nil {
23+ panic (err )
24+ }
25+
26+ defer func () {
27+ if err = client .Disconnect (ctx ); err != nil {
28+ panic (err )
29+ }
30+ }()
31+
32+ // Ping the primary
33+ if err := client .Ping (ctx , readpref .Primary ()); err != nil {
34+ panic (err )
35+ }
36+
37+ fmt .Println ("Successfully connected and pinged." )
38+ }
You can’t perform that action at this time.
0 commit comments