Skip to content

Commit 7e13909

Browse files
committed
Add count method based on find method
1 parent 5655997 commit 7e13909

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

sleepymongoose/handlers.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,48 @@ def _authenticate(self, args, out, name = None, db = None, collection = None):
203203
else:
204204
out('{"ok" : 1}')
205205

206+
def _count(self, args, out, name = None, db = None, collection = None):
207+
"""
208+
query the database.
209+
"""
210+
211+
if type(args).__name__ != 'dict':
212+
out('{"ok" : 0, "errmsg" : "_find must be a GET request"}')
213+
return
214+
215+
conn = self._get_connection(name)
216+
if conn == None:
217+
out('{"ok" : 0, "errmsg" : "couldn\'t get connection to mongo"}')
218+
return
219+
220+
if db == None or collection == None:
221+
out('{"ok" : 0, "errmsg" : "db and collection must be defined"}')
222+
return
223+
224+
criteria = {}
225+
if 'criteria' in args:
226+
criteria = self._get_son(args['criteria'][0], out)
227+
if criteria == None:
228+
return
229+
230+
fields = None
231+
if 'fields' in args:
232+
fields = self._get_son(args['fields'][0], out)
233+
if fields == None:
234+
return
235+
236+
limit = 0
237+
if 'limit' in args:
238+
limit = int(args['limit'][0])
239+
240+
skip = 0
241+
if 'skip' in args:
242+
skip = int(args['skip'][0])
243+
244+
count = conn[db][collection].find(spec=criteria, fields=fields, limit=limit, skip=skip).count()
245+
246+
out(json.dumps({"count": count}, default=json_util.default))
247+
206248
def _find(self, args, out, name = None, db = None, collection = None):
207249
"""
208250
query the database.

0 commit comments

Comments
 (0)