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