@@ -60,12 +60,8 @@ def count(self, limit=None, skip=None):
60
60
Return the number of objects that would be returned, if this query was
61
61
executed, up to `limit`, skipping `skip`.
62
62
"""
63
- kwargs = {}
64
- if limit is not None :
65
- kwargs ["limit" ] = limit
66
- if skip is not None :
67
- kwargs ["skip" ] = skip
68
- return self .collection .count_documents (self .mongo_query , ** kwargs )
63
+ result = list (self .get_cursor (count = True , limit = limit , skip = skip ))
64
+ return result [0 ]["__count" ] if result else 0
69
65
70
66
def order_by (self , ordering ):
71
67
"""
@@ -91,7 +87,16 @@ def delete(self):
91
87
options = self .connection .operation_flags .get ("delete" , {})
92
88
return self .collection .delete_many (self .mongo_query , ** options ).deleted_count
93
89
94
- def get_cursor (self ):
90
+ def get_cursor (self , count = False , limit = None , skip = None ):
91
+ """
92
+ Return a pymongo CommandCursor that can be iterated on to give the
93
+ results of the query.
94
+
95
+ If `count` is True, return a single document with the number of
96
+ documents that match the query.
97
+
98
+ Use `limit` or `skip` to override those options of the query.
99
+ """
95
100
if self .query .low_mark == self .query .high_mark :
96
101
return []
97
102
fields = {}
@@ -125,10 +130,16 @@ def get_cursor(self):
125
130
pipeline .append ({"$project" : fields })
126
131
if self .ordering :
127
132
pipeline .append ({"$sort" : dict (self .ordering )})
128
- if self .query .low_mark > 0 :
133
+ if skip is not None :
134
+ pipeline .append ({"$skip" : skip })
135
+ elif self .query .low_mark > 0 :
129
136
pipeline .append ({"$skip" : self .query .low_mark })
130
- if self .query .high_mark is not None :
137
+ if limit is not None :
138
+ pipeline .append ({"$limit" : limit })
139
+ elif self .query .high_mark is not None :
131
140
pipeline .append ({"$limit" : self .query .high_mark - self .query .low_mark })
141
+ if count :
142
+ pipeline .append ({"$group" : {"_id" : None , "__count" : {"$sum" : 1 }}})
132
143
return self .collection .aggregate (pipeline )
133
144
134
145
0 commit comments