-
Notifications
You must be signed in to change notification settings - Fork 0
/
find.go
88 lines (63 loc) · 1.67 KB
/
find.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
package mongogo
import (
"context"
"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"
)
func (m *Mongo[T]) Find(query interface{}, filter string) ([]T, error) {
collection := m.GetCollection()
var opts *options.FindOptions
if len(filter) > 0 {
opts = options.Find().SetProjection(createSelectFilter(filter))
}
cursor, err := collection.Find(context.Background(), query, opts)
if err != nil {
return nil, err
}
var results []T
if err = cursor.All(context.Background(), &results); err != nil {
return nil, err
}
return results, nil
}
func (m *Mongo[T]) FindOne(query interface{}, filter string) (*T, error) {
collection := m.GetCollection()
var opts *options.FindOneOptions
if len(filter) > 0 {
opts = options.FindOne().SetProjection(createSelectFilter(filter))
}
found := collection.FindOne(context.Background(), query, opts)
entity := new(T)
err := found.Decode(entity)
if err != nil {
if err == mongo.ErrNoDocuments {
return nil, nil
}
return nil, err
}
return entity, nil
}
func (m *Mongo[T]) FindOneById(id, filter string) (*T, error) {
objectId, err := primitive.ObjectIDFromHex(id)
if err != nil {
return nil, err
}
return m.FindOne(bson.D{
{Key: "_id", Value: objectId},
}, "")
}
func (M *Mongo[T]) FindByIds(ids []string, filter string) ([]T, error) {
var oids []primitive.ObjectID
for _, val := range ids {
oid, err := primitive.ObjectIDFromHex(val)
if err != nil {
continue
}
oids = append(oids, oid)
}
return M.Find(bson.D{
{Key: "_id", Value: bson.D{{Key: "$in", Value: oids}}},
}, filter)
}