-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonggo.go
300 lines (253 loc) · 7.13 KB
/
monggo.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package monggo
import (
"context"
"fmt"
"log"
"reflect"
"sync"
utils "github.com/nikkerella/gutils"
"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"
)
// Iter includes a MongoDB cursor and a mutex for thread-safe.
type Iter struct {
m sync.Mutex
cur *mongo.Cursor
err error
}
// NewIter initializes and returns a new Iter instance.
func NewIter(cur *mongo.Cursor, err error) *Iter {
return &Iter{
cur: cur,
err: err,
}
}
// Next advances the cursor to the next document
// and decodes it into the provided value.
func (iter *Iter) Next(T any) bool {
// Lock the mutex to ensure safe concurrent access to the cursor.
iter.m.Lock()
// Ensure the mutex is unlocked when the function returns.
defer iter.m.Unlock()
// Get the next document for the cursor
if iter.cur.Next(context.TODO()) {
// Decode the current document into the provided value T.
err := iter.cur.Decode(T)
if err != nil {
log.Println(err)
return false
}
} else {
// If there are no more documents to read then return false.
return false
}
// Return true if the document was sucessfully retrieved and decoded.
return true
}
func Aggregate(col *mongo.Collection, pipe []bson.D, T any) error {
cur, err := col.Aggregate(context.TODO(), pipe)
iter := NewIter(cur, err)
if err != nil {
log.Println(err)
return err
}
resultv := reflect.ValueOf(T)
if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice {
panic("Result argument must be a slice address")
}
slicev := resultv.Elem()
slicev = slicev.Slice(0, slicev.Cap())
elemt := slicev.Type().Elem()
i := 0
for {
if slicev.Len() == i {
elemp := reflect.New(elemt)
if !iter.Next(elemp.Interface()) {
break
}
slicev = reflect.Append(slicev, elemp.Elem())
slicev = slicev.Slice(0, slicev.Cap())
} else {
if !iter.Next(slicev.Index(i).Addr().Interface()) {
break
}
}
i++
}
resultv.Elem().Set(slicev.Slice(0, i))
return cur.Close(context.TODO())
}
func Count(col *mongo.Collection, filter bson.D) (int64, error) {
return col.CountDocuments(context.TODO(), filter)
}
// DeleteID deletes a document from the specified MongoDB collection
// based on the provided id.
func DeleteID(col *mongo.Collection, id any) error {
// Variable to hold the ObjectID to be deleted.
var objID primitive.ObjectID
// Use a type switch to determine the actual type of id
switch value := id.(type) {
case string:
objID = utils.ObjID(value)
case primitive.ObjectID:
objID = value
default:
return fmt.Errorf("unsupported id type: %T", id)
}
_, err := col.DeleteOne(context.TODO(), bson.D{primitive.E{Key: "_id", Value: objID}})
return err
}
// Insert adds a new document to the specified MongoDB collection
// from the provided generic value T.
func Insert(col *mongo.Collection, T any) error {
_, err := col.InsertOne(context.TODO(), T)
if err != nil {
log.Println(err)
}
return err
}
func FindID(col *mongo.Collection, id any) *mongo.SingleResult {
var objID primitive.ObjectID
switch value := id.(type) {
case string:
objID = utils.ObjID(value)
case primitive.ObjectID:
objID = value
case nil:
return nil
}
return col.FindOne(context.TODO(), bson.D{primitive.E{Key: "_id", Value: objID}})
}
// FindMany retrives multiple documents from the specified MongoDB collection
// that match the provided filter and sorts them. The results are stored
// in the provided slice RESULTS. The function returns an error
// if the retrieval fails or if the parameter RESULTS
// is not a pointer to a a slice.
func FindMany(col *mongo.Collection, RESULTS any, filter bson.D, sorts bson.D) error {
// Create a new find options object
opts := options.Find()
// If sorts are provided, set the sort options.
if len(sorts) > 0 {
opts.SetSort(sorts)
}
// Execute the find query with the given filter and options
cur, err := col.Find(context.TODO(), filter, opts)
if err != nil {
log.Println(err)
return err
}
// Initialize a new iterator with the cursor
iter := NewIter(cur, err)
// Use reflection to check if RESULTS is a pointer to a slice
resultv := reflect.ValueOf(RESULTS)
// Check the T is a slice address
if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice {
panic("Result argument must be a slice address")
}
// Initialize the slice value and element type
slicev := resultv.Elem()
slicev = slicev.Slice(0, slicev.Cap())
elemt := slicev.Type().Elem()
i := 0
// Interate over the cursor and append results to the slice
for {
// Check if the current slice length equals the index
if slicev.Len() == i {
// Create a new element pointer
elemp := reflect.New(elemt)
// Decode the nexr document into the element pointer
if !iter.Next(elemp.Interface()) {
break
}
// Append the element to the slice
slicev = reflect.Append(slicev, elemp.Elem())
slicev = slicev.Slice(0, slicev.Cap())
} else {
// Decode the next document into the existing slice element
if !iter.Next(slicev.Index(i).Addr().Interface()) {
break
}
}
i++
}
// Set the final slice with the results
resultv.Elem().Set(slicev.Slice(0, i))
// Close the cursor and return any error encountered during closing
return cur.Close(context.TODO())
}
// FindOne retrieves a single document from the specified MongoDB Collection
// that matches the provided filter.
func FindOne(col *mongo.Collection, filter any) *mongo.SingleResult {
return col.FindOne(context.TODO(), filter)
}
// Return total pages
func FindPage(col *mongo.Collection, T any, filter bson.D, page, limit int, sorts bson.D) (int, error) {
_page := int64(page)
_limit := int64(limit)
opts := options.Find()
if len(sorts) > 0 {
opts.SetSort(sorts)
}
if _page <= 0 {
_page = 1
}
cnt, err := Count(col, filter)
if err != nil {
return 0, err
}
totalPages := cnt / _limit
if cnt%_limit > 0 {
totalPages += 1
}
if totalPages == 0 {
totalPages = 1
}
opts.SetSkip(int64((_page - 1) * _limit)).SetLimit(_limit)
cur, err := col.Find(context.TODO(), filter, opts)
if err != nil {
log.Println(err)
return 0, err
}
iter := NewIter(cur, err)
resultv := reflect.ValueOf(T)
if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice {
panic("Result argument must be a slice address")
}
slicev := resultv.Elem()
slicev = slicev.Slice(0, slicev.Cap())
elemt := slicev.Type().Elem()
i := 0
for {
if slicev.Len() == i {
elemp := reflect.New(elemt)
if !iter.Next(elemp.Interface()) {
break
}
slicev = reflect.Append(slicev, elemp.Elem())
slicev = slicev.Slice(0, slicev.Cap())
} else {
if !iter.Next(slicev.Index(i).Addr().Interface()) {
break
}
}
i++
}
resultv.Elem().Set(slicev.Slice(0, i))
cur.Close(context.TODO())
return int(totalPages), nil
}
func Update(col *mongo.Collection, id any, upd any) error {
var objID primitive.ObjectID
switch id.(type) {
case string:
objID = utils.ObjID(fmt.Sprintf("%v", id))
case primitive.ObjectID:
objID = id.(primitive.ObjectID)
default:
return nil
}
_, err := col.UpdateOne(context.TODO(), bson.D{primitive.E{Key: "_id", Value: objID}}, upd)
return err
}