forked from mongodb/mongo-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
56 lines (49 loc) · 1.35 KB
/
query.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
package db
import (
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
mopt "go.mongodb.org/mongo-driver/mongo/options"
)
// DeferredQuery represents a deferred query
type DeferredQuery struct {
Coll *mongo.Collection
Filter interface{}
Hint interface{}
LogReplay bool
}
// Count issues a EstimatedDocumentCount command when there is no Filter in the query and a CountDocuments command otherwise.
func (q *DeferredQuery) Count(isView bool) (int, error) {
emptyFilter := false
filter := q.Filter
if q.Filter == nil {
emptyFilter = true
filter = bson.D{}
} else if val, ok := q.Filter.(bson.D); ok && (val == nil || len(val.Map()) == 0) {
emptyFilter = true
} else if val, ok := q.Filter.(bson.M); ok && (val == nil || len(val) == 0) {
emptyFilter = true
}
if emptyFilter && !isView {
opt := mopt.EstimatedDocumentCount()
c, err := q.Coll.EstimatedDocumentCount(nil, opt)
return int(c), err
}
opt := mopt.Count()
c, err := q.Coll.CountDocuments(nil, filter, opt)
return int(c), err
}
// Iter executes a find query and returns a cursor.
func (q *DeferredQuery) Iter() (*mongo.Cursor, error) {
opts := mopt.Find()
if q.Hint != nil {
opts.SetHint(q.Hint)
}
if q.LogReplay {
opts.SetOplogReplay(true)
}
filter := q.Filter
if filter == nil {
filter = bson.D{}
}
return q.Coll.Find(nil, filter, opts)
}