-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaggregate.go
67 lines (56 loc) · 1.49 KB
/
aggregate.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
package mongolib
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type Aggregate struct {
coll *Collection
pipeline mongo.Pipeline
}
func (a Aggregate) Match(filter filter) Aggregate {
a.pipeline = append(a.pipeline, bson.D{{"$match", bson.D{{"$and", filter}}}})
return a
}
func (a Aggregate) Sort(key string, order int) Aggregate {
a.pipeline = append(a.pipeline, bson.D{{"$sort", bson.D{{key, order}}}})
return a
}
func (a Aggregate) Limit(limit int) Aggregate {
a.pipeline = append(a.pipeline, bson.D{{"$limit", limit}})
return a
}
func (a Aggregate) Offset(offset int) Aggregate {
a.pipeline = append(a.pipeline, bson.D{{"$skip", offset}})
return a
}
func (a Aggregate) Lookup(from, localField, foreignField, as string) Aggregate {
a.pipeline = append(a.pipeline, bson.D{{"$lookup", bson.D{
{"from", from},
{"localField", localField},
{"foreignField", foreignField},
{"as", as},
}}})
return a
}
func (a Aggregate) Unwind(field string) Aggregate {
a.pipeline = append(a.pipeline, bson.D{{"$unwind", field}})
return a
}
func (a Aggregate) AddField(fieldName string, value interface{}) Aggregate {
a.pipeline = append(a.pipeline, bson.D{{"$addFields", bson.D{{fieldName, value}}}})
return a
}
func (a Aggregate) Exec(ctx context.Context) Result {
cur, err := a.coll.Collection.Aggregate(ctx, a.pipeline)
if err != nil {
return &MultipleResult{
Cursor: nil,
Error: err,
}
}
return &MultipleResult{
Cursor: cur,
Error: nil,
}
}