summaryrefslogtreecommitdiffstats
path: root/src/mongo.go
diff options
context:
space:
mode:
Diffstat (limited to 'src/mongo.go')
-rw-r--r--src/mongo.go79
1 files changed, 79 insertions, 0 deletions
diff --git a/src/mongo.go b/src/mongo.go
new file mode 100644
index 0000000..d00abd2
--- /dev/null
+++ b/src/mongo.go
@@ -0,0 +1,79 @@
1package main
2
3import (
4 "context"
5 "time"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12type mongoClient struct {
13 dbName, colName string
14 client *mongo.Client
15 col *mongo.Collection
16}
17
18func (mc *mongoClient) Connect(dbName, colName string) error {
19 var err error
20 mc.client, err = mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
21
22 if err != nil {
23 return err
24 }
25
26 ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
27 err = mc.client.Connect(ctx)
28 if err != nil {
29 return err
30 }
31
32 mc.col = mc.client.Database(dbName).Collection(colName)
33 mc.dbName = dbName
34 mc.colName = colName
35 return nil
36}
37
38func (mc *mongoClient) InsertOne(document interface{}) error {
39 _, err := mc.col.InsertOne(context.Background(), document)
40 return err
41}
42
43func (mc *mongoClient) UpdateOne(filter, update interface{}) error {
44 _, err := mc.col.UpdateOne(context.Background(), filter, update)
45 return err
46}
47
48func (mc *mongoClient) UpdateMany(filter, update interface{}) error {
49 _, err := mc.col.UpdateMany(context.Background(), filter, update)
50 return err
51}
52
53func (mc *mongoClient) Finddoc(filter bson.M) ([]bson.M, error) {
54 cur, err := mc.col.Find(context.Background(), filter)
55 if err != nil {
56 return nil, err
57 }
58
59 var results []bson.M
60 err = cur.All(context.Background(), &results)
61
62 return results, err
63}
64
65func (mc *mongoClient) Drop() error {
66 return mc.col.Drop(context.Background())
67}
68
69func (mc *mongoClient) Disconnect() error {
70 err := mc.client.Disconnect(context.Background())
71 if err != nil {
72 return err
73 }
74 mc.col = nil
75 mc.client = nil
76 mc.dbName = ""
77 mc.colName = ""
78 return nil
79}