summaryrefslogtreecommitdiffstats
path: root/src/mongo.go
blob: d00abd23479e38788adeabc62a6a10ce91c44575 (plain) (blame)
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
69
70
71
72
73
74
75
76
77
78
79
package main

import (
	"context"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type mongoClient struct {
	dbName, colName string
	client          *mongo.Client
	col             *mongo.Collection
}

func (mc *mongoClient) Connect(dbName, colName string) error {
	var err error
	mc.client, err = mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))

	if err != nil {
		return err
	}

	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	err = mc.client.Connect(ctx)
	if err != nil {
		return err
	}

	mc.col = mc.client.Database(dbName).Collection(colName)
	mc.dbName = dbName
	mc.colName = colName
	return nil
}

func (mc *mongoClient) InsertOne(document interface{}) error {
	_, err := mc.col.InsertOne(context.Background(), document)
	return err
}

func (mc *mongoClient) UpdateOne(filter, update interface{}) error {
	_, err := mc.col.UpdateOne(context.Background(), filter, update)
	return err
}

func (mc *mongoClient) UpdateMany(filter, update interface{}) error {
	_, err := mc.col.UpdateMany(context.Background(), filter, update)
	return err
}

func (mc *mongoClient) Finddoc(filter bson.M) ([]bson.M, error) {
	cur, err := mc.col.Find(context.Background(), filter)
	if err != nil {
		return nil, err
	}

	var results []bson.M
	err = cur.All(context.Background(), &results)

	return results, err
}

func (mc *mongoClient) Drop() error {
	return mc.col.Drop(context.Background())
}

func (mc *mongoClient) Disconnect() error {
	err := mc.client.Disconnect(context.Background())
	if err != nil {
		return err
	}
	mc.col = nil
	mc.client = nil
	mc.dbName = ""
	mc.colName = ""
	return nil
}