...
1
2
3
4
5
6
7 package main
8
9 import (
10 "context"
11 "log"
12 "os"
13 "time"
14
15 "go.mongodb.org/mongo-driver/mongo"
16 "go.mongodb.org/mongo-driver/mongo/options"
17 "go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
18 )
19
20 func main() {
21 uri := os.Getenv("MONGODB_URI")
22 compressor := os.Getenv("MONGO_GO_DRIVER_COMPRESSOR")
23
24 client, err := mongo.Connect(
25 context.Background(),
26 options.Client().ApplyURI(uri).SetCompressors([]string{compressor}))
27 if err != nil {
28 log.Fatalf("Error connecting client: %v", err)
29 }
30
31
32
33 cs, err := connstring.Parse(uri)
34 if err != nil {
35 log.Fatalf("Error parsing connection string: %v", err)
36 }
37 if cs.Database == "" {
38 log.Fatal("Connection string must contain a defaultauthdb.")
39 }
40
41 coll := client.Database(cs.Database).Collection("test")
42
43 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
44 defer cancel()
45
46 count, err := coll.EstimatedDocumentCount(ctx)
47 if err != nil {
48 log.Fatalf("failed executing count command: %v", err)
49 }
50 log.Println("Count of test collection:", count)
51 }
52
View as plain text