@@ -51,6 +51,7 @@ To get started with the driver, import the `mongo` package, create a `mongo.Clie
51
51
import (
52
52
" go.mongodb.org/mongo-driver/mongo"
53
53
" go.mongodb.org/mongo-driver/mongo/options"
54
+ " go.mongodb.org/mongo-driver/mongo/readpref"
54
55
)
55
56
56
57
client , err := mongo.NewClient (options.Client ().ApplyURI (" mongodb://localhost:27017" ))
@@ -59,17 +60,29 @@ client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27
59
60
And connect it to your running MongoDB server:
60
61
61
62
``` go
62
- ctx , _ := context.WithTimeout (context.Background (), 10 *time.Second )
63
+ ctx , cancel := context.WithTimeout (context.Background (), 10 *time.Second )
64
+ defer cancel ()
63
65
err = client.Connect (ctx)
64
66
```
65
67
66
68
To do this in a single step, you can use the ` Connect ` function:
67
69
68
70
``` go
69
- ctx , _ := context.WithTimeout (context.Background (), 10 *time.Second )
71
+ ctx , cancel := context.WithTimeout (context.Background (), 10 *time.Second )
72
+ defer cancel ()
70
73
client , err := mongo.Connect (ctx, options.Client ().ApplyURI (" mongodb://localhost:27017" ))
71
74
```
72
75
76
+ Make sure to defer a call to ` Disconnect ` after instantiating your client:
77
+
78
+ ``` go
79
+ defer func () {
80
+ if err = client.Disconnect (ctx); err != nil {
81
+ panic (err)
82
+ }
83
+ }()
84
+ ```
85
+
73
86
Calling ` Connect ` does not block for server discovery. If you wish to know if a MongoDB server has been found and connected to,
74
87
use the ` Ping ` method:
75
88
0 commit comments