forked from romnn/testcontainers
/
mongo.go
45 lines (40 loc) · 1.19 KB
/
mongo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
"context"
"log"
"time"
tcmongo "github.com/mmadfox/testcontainers/mongo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
container, err := tcmongo.Start(context.Background(), tcmongo.Options{
ImageTag: "6.0.2", // you could use latest here
})
if err != nil {
log.Fatalf("failed to start container: %v", err)
}
defer container.Terminate(context.Background())
// connect to the container
uri := container.ConnectionURI()
client, err := mongo.NewClient(options.Client().ApplyURI(uri))
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client.Connect(ctx)
// count documents in collection
collection := client.Database("testdatabase").Collection("my-collection")
opts := options.Count().SetMaxTime(2 * time.Second)
count, err := collection.CountDocuments(
context.TODO(),
bson.D{},
opts,
)
if err != nil {
log.Fatalf("failed to count docs in collection %q: %v", collection.Name(), err)
}
log.Printf("collection %q contains %d documents", collection.Name(), count)
}