-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.go
41 lines (34 loc) · 858 Bytes
/
mongo.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
package mongolog
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Config struct {
URI string // MongoDB URI
DBName string // Database name
}
type MongoLogDB struct {
db *mongo.Database
}
func NewMongoDB(cfg Config) (*MongoLogDB, error) {
client, err := connect(cfg.URI)
if err != nil {
return nil, err
}
db := client.Database(cfg.DBName)
return &MongoLogDB{
db: db,
}, nil
}
func (m *MongoLogDB) Insert(ctx context.Context, collection string, data map[string]interface{}) error {
col := m.db.Collection(collection)
_, err := col.InsertOne(ctx, data)
return err
}
func connect(uri string) (*mongo.Client, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return mongo.Connect(ctx, options.Client().ApplyURI(uri))
}