Permalink
Browse files

I've added a count() method which I needed.

  • Loading branch information...
1 parent 7f75809 commit dfd9f0bae577dab50f2f79bab33987dfe70008a3 @bcoe committed Jan 7, 2011
Showing with 42 additions and 5 deletions.
  1. +4 −0 README.textile
  2. +16 −4 mongate/collection.py
  3. +1 −1 setup.py
  4. +21 −0 tests/collection.py
View
@@ -26,6 +26,10 @@ or
*collection.find_one({'key': 'value'})*
+h3. Count Data
+
+*collection.count({'key': 'value'})*
+
h3. Update Data
*collection.update({'key': 'value'}, {'$set': {'key': 'value'}})*
View
@@ -83,6 +83,10 @@ def remove(self, criteria={}):
def _create_remove_payload(self, criteria):
return "criteria=%s" % json.dumps(criteria)
+ def count(self, criteria):
+ results = self.find(criteria, ['_id'])
+ return len(results)
+
def find_one(self, criteria):
"""
Return the first result fetched by find.
@@ -93,14 +97,14 @@ def find_one(self, criteria):
else:
return False
- def find(self, criteria={}):
+ def find(self, criteria={}, fields=False):
"""
Find all documents matching the criteria, e.g.,
{'foo': {'$lt': 5}}
"""
criteria = self._replace_id_with_object(criteria)
url = self._create_url(self.find_action)
- get_params = self._create_find_get_params(criteria)
+ get_params = self._create_find_get_params(criteria, fields)
response_object = self.connection.perform_request(
url,
get_params=get_params,
@@ -114,10 +118,18 @@ def _process_response_object(self, response_object):
result['_id'] = result['_id']['$oid']
return response_object['results']
- def _create_find_get_params(self, criteria):
- return "?batch_size=9999999&criteria=%s" % urllib.quote(
+ def _create_find_get_params(self, criteria, fields=False):
+ params = "?batch_size=9999999&criteria=%s" % urllib.quote(
json.dumps(criteria)
)
+ if fields:
+ params = "%s&fields=%s" % (
+ params,
+ urllib.quote(
+ json.dumps(fields)
+ )
+ )
+ return params
def _replace_id_with_object(self, criteria):
if criteria.has_key('_id'):
View
@@ -4,7 +4,7 @@
setup(
name="mongate",
- version="2.1.0",
+ version="2.1.5",
description="A client library for Sleepy Mongoose that provides the same interface as Pymongo. With support for batch operations.",
author="Benjamin Coe",
author_twitter="@benjamincoe",
View
@@ -190,6 +190,27 @@ def test_save_creates_document_if_it_does_not_exist(self):
})
self.assertEqual('Bob', retrieved_collection['name'])
+
+ def test_count_with_zero_results(self):
+ count = self.collection.count({'foo': 'bar'})
+ self.assertEqual(0, count)
+
+ def test_count_with_zero_results(self):
+ self.collection.save({
+ 'name': 'Bob',
+ 'age': 'old'
+ })
+ self.collection.save({
+ 'name': 'Bob',
+ 'age': 'old'
+ })
+ self.collection.save({
+ 'name': 'Bob',
+ 'age': 'old'
+ })
+
+ count = self.collection.count({'name': 'Bob'})
+ self.assertEqual(3, count)
if __name__ == "__main__":
unittest.main()

0 comments on commit dfd9f0b

Please sign in to comment.