From 62bda75112662780b0d2576e8f594111c10a7578 Mon Sep 17 00:00:00 2001 From: Harry Marr Date: Sat, 2 Jan 2010 20:42:18 +0000 Subject: [PATCH] Added aggregation methods to user guide --- docs/userguide.rst | 49 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/docs/userguide.rst b/docs/userguide.rst index 56bf9c97..ce4d18db 100644 --- a/docs/userguide.rst +++ b/docs/userguide.rst @@ -295,7 +295,7 @@ Just as with traditional ORMs, you may limit the number of results returned, or skip a number or results in you query. :meth:`mongoengine.queryset.QuerySet.limit` and :meth:`mongoengine.queryset.QuerySet.skip` and methods are available on -:meth:`mongoengine.queryset.QuerySet` objects, but the prefered syntax for +:class:`mongoengine.queryset.QuerySet` objects, but the prefered syntax for achieving this is using array-slicing syntax:: # Only the first 5 people @@ -306,3 +306,50 @@ achieving this is using array-slicing syntax:: # 5 users, starting from the 10th user found users = User.objects[10:15] + +Aggregation +----------- +MongoDB provides some aggregation methods out of the box, but there are not as +many as you typically get with an RDBMS. MongoEngine provides a wrapper around +the built-in methods and provides some of its own, which are implemented as +Javascript code that is executed on the database server. + +Counting results +^^^^^^^^^^^^^^^^ +Just as with limiting and skipping results, there is a method on +:class:`mongoengine.queryset.QuerySet` objects -- +:meth:`mongoengine.queryset.QuerySet.count`, but there is also a more Pythonic +way of achieving this:: + + num_users = len(User.objects) + +Further aggregation +^^^^^^^^^^^^^^^^^^^ +You may sum over the values of a specific field on documents using +:meth:`mongoengine.queryset.QuerySet.sum`:: + + yearly_expense = Employee.objects.sum('salary') + +.. note:: + If the field isn't present on a document, that document will be ignored from + the sum. + +To get the average (mean) of a field on a collection of documents, use +:meth:`mongoengine.queryset.QuerySet.average`:: + + mean_age = User.objects.average('age') + +As MongoDB provides native lists, MongoEngine provides a helper method to get a +dictionary of the frequencies of items in lists across an entire collection -- +:meth:`mongoengine.queryset.QuerySet.item_frequencies`. An example of its use +would be generating "tag-clouds":: + + class Article(Document): + tag = ListField(StringField()) + + # After adding some tagged articles... + tag_freqs = Article.objects.item_frequencies('tag', normalize=True) + + from operator import itemgetter + top_tags = sorted(tag_freqs.items(), key=itemgetter(1), reverse=True)[:10] +