-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·68 lines (54 loc) · 1.74 KB
/
main.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package main
import (
"context"
"log"
"time"
"flag"
"github.com/Vincent20101/mongo-go-driver/bson"
"github.com/Vincent20101/mongo-go-driver/core/command"
"github.com/Vincent20101/mongo-go-driver/core/connstring"
"github.com/Vincent20101/mongo-go-driver/core/description"
"github.com/Vincent20101/mongo-go-driver/core/dispatch"
"github.com/Vincent20101/mongo-go-driver/core/topology"
)
var uri = flag.String("uri", "mongodb://localhost:27017", "the mongodb uri to use")
var col = flag.String("c", "test", "the collection name to use")
func main() {
flag.Parse()
if *uri == "" {
log.Fatalf("uri flag must have a value")
}
cs, err := connstring.Parse(*uri)
if err != nil {
log.Fatal(err)
}
t, err := topology.New(topology.WithConnString(func(connstring.ConnString) connstring.ConnString { return cs }))
if err != nil {
log.Fatal(err)
}
err = t.Connect(context.Background())
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
dbname := cs.Database
if dbname == "" {
dbname = "test"
}
cmd := command.Read{DB: dbname, Command: bson.NewDocument(bson.EC.String("count", *col))}
rdr, err := dispatch.Read(ctx, cmd, t, description.WriteSelector())
if err != nil {
log.Fatalf("failed executing count command on %s.%s: %v", dbname, *col, err)
}
result, err := bson.ToExtJSON(true, rdr)
if err != nil {
log.Fatalf("failed to convert BSON to extended JSON: %s", err)
}
log.Println(result)
}