/
main.go
271 lines (191 loc) · 5.92 KB
/
main.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// gomongoclient implements and simplify the mongodb-driver usage
package gomongoclient
import (
"context"
"fmt"
"log"
"time"
"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"
)
type MongoDB struct {
Host string
Port int
User string
Password string
Database string
client mongo.Client
}
// Init the basic connection
func (m *MongoDB) Init() (err error) {
if m.client, err = m.connect(); err != nil {
fmt.Printf("[ERROR]: Can't connect to the host: [%s]. [Err Detail: %s]\n ", m.Host, err)
}
return
}
// Done close all connections to this stance and free all the cache
func (m *MongoDB) Done() (err error) {
if err = m.client.Disconnect(context.TODO()); err != nil {
fmt.Printf("[ERROR]: No connection to close. [Err Detail: %s]\n", err)
}
return
}
// connect to the mongo databse
func (m *MongoDB) connect() (mongo.Client, error) {
uri := fmt.Sprintf("mongodb://%s:%s@%s:%v", m.User, m.Password, m.Host, m.Port)
clientOptions := options.Client().ApplyURI(uri)
// Connect to MongoDB
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
fmt.Printf("failed to connect to the mongo server %v", err)
}
// Test Connection
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err = client.Ping(ctx, readpref.Primary())
return *client, err
}
func (m *MongoDB) Test() string {
return "test"
}
// Ping tests the connection with the mongo Server
func (m *MongoDB) Ping(connectOnFailure bool) (err error) {
if err = m.client.Ping(context.TODO(), nil); err != nil {
if connectOnFailure {
err = m.Init()
}
}
return
}
// Find the values from given query
func (m *MongoDB) Find(collection string, query interface{}, limit int64) (result []bson.M, err error) {
if err = m.Ping(true); err != nil {
return
}
options := options.Find()
options.SetLimit(limit)
col := m.client.Database(m.Database).Collection(collection)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cur, err := col.Find(ctx, query, options)
if err != nil {
log.Printf("[ERROR]: Failed to execute the search query. [Err Detail: %s]", err)
return
}
defer cur.Close(ctx)
for cur.Next(ctx) {
var res bson.M
err = cur.Decode(&res)
result = append(result, res)
if err != nil {
log.Printf("[ERROR]: ToDo1 error message. [Err Detail: %s]", err)
return
}
}
return
}
// FindAndConvert return the mongo cursor to use in struct conversion
func (m *MongoDB) FindAndConvert(collection string, query interface{}, sort interface{}, limit int64) (cur *mongo.Cursor, err error) {
if err = m.Ping(true); err != nil {
return
}
options := options.Find()
options.SetLimit(limit)
options.SetSort(sort)
col := m.client.Database(m.Database).Collection(collection)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cur, err = col.Find(ctx, query, options)
if err != nil {
log.Printf("[ERROR]: Failed to execute the search query. [Err Detail: %s]", err)
}
return
}
// Insert a new Value to the Collection
func (m *MongoDB) Insert(collection string, query interface{}) error {
if err := m.Ping(true); err != nil {
return err
}
col := m.client.Database(m.Database).Collection(collection)
// TODO - TTL Index
// mod := mongo.IndexModel{
// Keys: bson.M{
// "ExpireAt": 1, // index in ascending order
// }, Options: options.Index().SetExpireAfterSeconds(0),
// }
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// ind, err := col.Indexes().CreateOne(ctx, mod)
// if err != nil {
// fmt.Println(err)
// }
// fmt.Println(ind)
_, err := col.InsertOne(ctx, query)
if err != nil {
return fmt.Errorf("[MONGO]: Insert failed. [Err Detail: %s]", err)
}
return nil
}
func (m *MongoDB) Upsert(collection string, values bson.M, filter bson.M) error {
if err := m.Ping(true); err != nil {
return err
}
col := m.client.Database(m.Database).Collection(collection)
opts := options.Update()
opts.SetUpsert(true)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := col.UpdateOne(ctx, filter, values, opts)
if err != nil {
return fmt.Errorf("[MONGO]: Upsert failed. [Err Detail: %s]", err)
}
return nil
}
func (m *MongoDB) Update(collection string, filter bson.M, update bson.M) {
if err := m.Ping(true); err != nil {
return
}
col := m.client.Database(m.Database).Collection(collection)
_, err := col.UpdateMany(context.TODO(), filter, update)
if err != nil {
fmt.Println(err)
}
}
// UpsertMany records on the mongo database
func (m *MongoDB) UpsertMany(collection string, query interface{}, filter interface{}) {
if err := m.Ping(true); err != nil {
return
}
col := m.client.Database(m.Database).Collection(collection)
var operations []mongo.WriteModel
operation := mongo.NewUpdateOneModel()
operation.SetFilter(filter)
operation.SetUpdate(bson.M{"$set": query})
operation.SetUpsert(true)
operations = append(operations, operation)
// Specify an option to turn the bulk insertion in order of operation
bulkOption := options.BulkWriteOptions{}
// bulkOption.SetOrdered(true)
_, err := col.BulkWrite(context.TODO(), operations, &bulkOption)
if err != nil {
(fmt.Printf("Mongo failed to Upsert Many, %v\n", err))
}
}
// InsertMany values to the given collection
func (m *MongoDB) InsertMany(collection string, query []interface{}, ordered bool) error {
if err := m.Ping(true); err != nil {
return err
}
col := m.client.Database(m.Database).Collection(collection)
opts := options.InsertManyOptions{}
opts.SetOrdered(ordered)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err := col.InsertMany(ctx, query, &opts)
if err != nil {
fmt.Printf("[MONGO]: Insert failed. [Err Detail: %s]", err)
}
return err
}