1// Copyright (C) MongoDB, Inc. 2017-present. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); you may 4// not use this file except in compliance with the License. You may obtain 5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 6 7package main 8 9import ( 10 "context" 11 "log" 12 "time" 13 14 "flag" 15 16 "go.mongodb.org/mongo-driver/mongo/description" 17 "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" 18 "go.mongodb.org/mongo-driver/x/mongo/driver/connstring" 19 "go.mongodb.org/mongo-driver/x/mongo/driver/operation" 20 "go.mongodb.org/mongo-driver/x/mongo/driver/topology" 21) 22 23var uri = flag.String("uri", "mongodb://localhost:27017", "the mongodb uri to use") 24var col = flag.String("c", "test", "the collection name to use") 25 26func main() { 27 28 flag.Parse() 29 30 if *uri == "" { 31 log.Fatalf("uri flag must have a value") 32 } 33 34 cs, err := connstring.ParseAndValidate(*uri) 35 if err != nil { 36 log.Fatal(err) 37 } 38 39 t, err := topology.New(topology.WithConnString(func(connstring.ConnString) connstring.ConnString { return cs })) 40 if err != nil { 41 log.Fatal(err) 42 } 43 err = t.Connect() 44 if err != nil { 45 log.Fatal(err) 46 } 47 48 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 49 defer cancel() 50 51 dbname := cs.Database 52 if dbname == "" { 53 dbname = "test" 54 } 55 56 op := operation.NewCommand(bsoncore.BuildDocument(nil, bsoncore.AppendStringElement(nil, "count", *col))). 57 Deployment(t).Database(dbname).ServerSelector(description.WriteSelector()) 58 err = op.Execute(ctx) 59 if err != nil { 60 log.Fatalf("failed executing count command on %s.%s: %v", dbname, *col, err) 61 } 62 rdr := op.Result() 63 log.Println(rdr) 64} 65