/
mongodb.go
70 lines (57 loc) · 1.83 KB
/
mongodb.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
69
70
package collector
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
// Represents a cursor to fetch records from
type Cursor interface {
Next(ctx context.Context) bool
Close(ctx context.Context) error
Decode(val interface{}) error
}
// MongoDB event stream
type ChangeStreamEventNamespace struct {
DB string
Coll string
}
// MongoDB event stream
type ChangeStreamEvent struct {
NS *ChangeStreamEventNamespace
}
// MongoDB aggregation result
type AggregationResult map[string]interface{}
// MongoDB driver abstraction
type Driver interface {
Connect(ctx context.Context, opts ...*options.ClientOptions) error
Ping(ctx context.Context, rp *readpref.ReadPref) error
Aggregate(ctx context.Context, db string, col string, pipeline bson.A) (Cursor, error)
Watch(ctx context.Context, db string, col string, pipeline bson.A) (Cursor, error)
}
// MongoDB driver
type MongoDBDriver struct {
client *mongo.Client
}
// Connect to the server
func (mdb *MongoDBDriver) Connect(ctx context.Context, opts ...*options.ClientOptions) error {
client, err := mongo.Connect(ctx, opts...)
if err != nil {
return err
}
mdb.client = client
return nil
}
// Enforce connection to the server
func (mdb *MongoDBDriver) Ping(ctx context.Context, rp *readpref.ReadPref) error {
return mdb.client.Ping(ctx, rp)
}
// Aggregation rquery
func (mdb *MongoDBDriver) Aggregate(ctx context.Context, db string, col string, pipeline bson.A) (Cursor, error) {
return mdb.client.Database(db).Collection(col).Aggregate(ctx, pipeline)
}
// Start an eventstream
func (mdb *MongoDBDriver) Watch(ctx context.Context, db string, col string, pipeline bson.A) (Cursor, error) {
return mdb.client.Database(db).Collection(col).Watch(ctx, pipeline)
}