@@ -87,7 +87,8 @@ Calling `Connect` does not block for server discovery. If you wish to know if a
87
87
use the ` Ping ` method:
88
88
89
89
``` go
90
- ctx, _ = context.WithTimeout (context.Background (), 2 *time.Second )
90
+ ctx, cancel = context.WithTimeout (context.Background (), 2 *time.Second )
91
+ defer cancel ()
91
92
err = client.Ping (ctx, readpref.Primary ())
92
93
```
93
94
@@ -100,15 +101,17 @@ collection := client.Database("testing").Collection("numbers")
100
101
The ` Collection ` instance can then be used to insert documents:
101
102
102
103
``` go
103
- ctx, _ = context.WithTimeout (context.Background (), 5 *time.Second )
104
+ ctx, cancel = context.WithTimeout (context.Background (), 5 *time.Second )
105
+ defer cancel ()
104
106
res , err := collection.InsertOne (ctx, bson.M {" name" : " pi" , " value" : 3.14159 })
105
107
id := res.InsertedID
106
108
```
107
109
108
110
Several query methods return a cursor, which can be used like this:
109
111
110
112
``` go
111
- ctx, _ = context.WithTimeout (context.Background (), 30 *time.Second )
113
+ ctx, cancel = context.WithTimeout (context.Background (), 30 *time.Second )
114
+ defer cancel ()
112
115
cur , err := collection.Find (ctx, bson.D {})
113
116
if err != nil { log.Fatal (err) }
114
117
defer cur.Close (ctx)
@@ -130,7 +133,8 @@ var result struct {
130
133
Value float64
131
134
}
132
135
filter := bson.M {" name" : " pi" }
133
- ctx, _ = context.WithTimeout (context.Background (), 5 *time.Second )
136
+ ctx, cancel = context.WithTimeout (context.Background (), 5 *time.Second )
137
+ defer cancel ()
134
138
err = collection.FindOne (ctx, filter).Decode (&result)
135
139
if err != nil {
136
140
log.Fatal (err)
0 commit comments