-
Notifications
You must be signed in to change notification settings - Fork 0
/
distinct.go
64 lines (53 loc) · 1.35 KB
/
distinct.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
package dbm
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
"reflect"
"time"
)
type Distinct interface {
Collation(c *Collation) Distinct
MaxTime(d time.Duration) Distinct
Apply(result interface{}) error
}
type distinct struct {
filter interface{}
fieldName string
ctx context.Context
opts *options.DistinctOptions
collection Collection
}
func (d *distinct) Collation(c *Collation) Distinct {
d.opts.SetCollation(c)
return d
}
func (d *distinct) MaxTime(duration time.Duration) Distinct {
d.opts.SetMaxTime(duration)
return d
}
func (d *distinct) Apply(result interface{}) error {
var resultValue = reflect.ValueOf(result)
if resultValue.Kind() != reflect.Ptr {
return ErrResultNotSlice
}
var resultElemKind = resultValue.Elem().Kind()
if resultElemKind != reflect.Interface && resultElemKind != reflect.Slice {
return ErrResultNotSlice
}
var data, err = d.collection.Collection().Distinct(d.ctx, d.fieldName, d.filter, d.opts)
if err != nil {
return err
}
valueType, valueBytes, err := bson.MarshalValueWithRegistry(d.collection.Database().Client().Registry(), data)
if err != nil {
return err
}
var rawValue = bson.RawValue{}
rawValue.Type = valueType
rawValue.Value = valueBytes
if err = rawValue.Unmarshal(result); err != nil {
return err
}
return nil
}