-
Notifications
You must be signed in to change notification settings - Fork 2
/
nosql-document-mongodb.go
208 lines (166 loc) · 5.53 KB
/
nosql-document-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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package storage
import (
"context"
"encoding/json"
"fmt"
"log"
"reflect"
"strings"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"github.com/golang-common-packages/hash"
)
// MongoClient manage all mongodb actions
type MongoClient struct {
Client *mongo.Client
Cancel context.CancelFunc
Config *MongoDB
}
var (
// mongoClientSessionMapping singleton pattern
mongoClientSessionMapping = make(map[string]*MongoClient)
)
// newMongoDB init new instance
func newMongoDB(config *MongoDB) INoSQLDocument {
hasher := &hash.Client{}
configAsJSON, err := json.Marshal(config)
if err != nil {
log.Fatalln("Unable to marshal MongoDB configuration: ", err)
}
configAsString := hasher.SHA1(string(configAsJSON))
currentMongoSession := mongoClientSessionMapping[configAsString]
if currentMongoSession == nil {
currentMongoSession = &MongoClient{nil, nil, nil}
// Establish MongoDB connection
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(getConnectionURI(config)))
if err != nil {
cancel()
log.Fatalln("Unable to connect to MongoDB: ", err)
}
// Check the connection status
if err = client.Ping(ctx, readpref.Primary()); err != nil {
cancel()
log.Fatalln("Unable to ping to MongoDB: ", err)
}
currentMongoSession.Client = client
currentMongoSession.Cancel = cancel
currentMongoSession.Config = config
mongoClientSessionMapping[configAsString] = currentMongoSession
log.Println("Connected to MongoDB")
}
return currentMongoSession
}
// getConnectionURL return mongo connection URI
func getConnectionURI(config *MongoDB) (URI string) {
host := strings.Join(config.Hosts, ",")
opt := strings.Join(config.Options, "?")
if config.User == "" && config.Password == "" {
return fmt.Sprintf("%v?%v", host, opt)
}
URI = fmt.Sprintf("mongodb+srv://%v:%v@%v/%v", config.User, config.Password, host, opt)
return URI
}
// createSession return a new mongo session & transaction
func (m *MongoClient) createSession() (session mongo.Session) {
session, err := m.Client.StartSession()
if err != nil {
log.Fatalln("Unable to init new session: ", err)
}
if err := session.StartTransaction(); err != nil {
log.Fatalln("Unable to start transaction: ", err)
}
return session
}
// Create the list of document on collection
func (m *MongoClient) Create(databaseName, collectionName string, documents []interface{}) (interface{}, error) {
var result interface{}
session := m.createSession()
defer session.EndSession(ctx)
if err := mongo.WithSession(ctx, session, func(sc mongo.SessionContext) (err error) {
collection := m.Client.Database(databaseName).Collection(collectionName)
result, err = collection.InsertMany(ctx, documents)
if err != nil {
log.Println("Unable to create document: ", err)
return err
}
return nil
}); err != nil {
log.Println("Unable to execute mongo session: ", err)
return nil, err
}
return result, nil
}
// Read documents from collection based on filter
func (m *MongoClient) Read(databaseName, collectionName string, filter interface{}, limit int64, dataModel reflect.Type) (interface{}, error) {
var results interface{}
session := m.createSession()
defer session.EndSession(ctx)
if err := mongo.WithSession(ctx, session, func(sc mongo.SessionContext) (err error) {
findOptions := options.Find()
findOptions.SetLimit(limit)
findOptions.SetSort(bson.D{primitive.E{Key: "_id", Value: 1}})
collection := m.Client.Database(databaseName).Collection(collectionName)
cur, err := collection.Find(ctx, filter, findOptions)
defer cur.Close(ctx)
if err != nil {
log.Println("Unable to read document: ", err)
return err
}
// Decode cursor
dataModel := reflect.Zero(reflect.SliceOf(dataModel)).Type()
results = reflect.New(dataModel).Interface()
err = cur.All(ctx, results)
if err != nil {
log.Println("Unable to decode cursor: ", err)
return err
}
return nil
}); err != nil {
log.Println("Unable to execute mongo session: ", err)
return nil, err
}
return results, nil
}
// Update document with new value based on filter condition
func (m *MongoClient) Update(databaseName, collectionName string, filter, update interface{}) (interface{}, error) {
var result interface{}
session := m.createSession()
defer session.EndSession(ctx)
if err := mongo.WithSession(ctx, session, func(sc mongo.SessionContext) (err error) {
collection := m.Client.Database(databaseName).Collection(collectionName)
result, err = collection.UpdateMany(ctx, filter, update)
if err != nil {
log.Println("Unable to update: ", err)
return err
}
return nil
}); err != nil {
log.Println("Unable to execute mongo session: ", err)
return nil, err
}
return result, nil
}
// Delete document based on filter condition
func (m *MongoClient) Delete(databaseName, collectionName string, filter interface{}) (interface{}, error) {
var result interface{}
session := m.createSession()
defer session.EndSession(ctx)
if err := mongo.WithSession(ctx, session, func(sc mongo.SessionContext) (err error) {
collection := m.Client.Database(databaseName).Collection(collectionName)
result, err = collection.DeleteMany(ctx, filter)
if err != nil {
log.Println("Unable to delete: ", err)
return err
}
return nil
}); err != nil {
log.Println("Unable to execute mongo session: ", err)
return nil, err
}
return result, nil
}