0

I want to count all the numbers of different values in a field.there is no "annotate()" to use in mongoengine ,then how could i count the number and order them by numbers

The only way i thought out to solve this is use"distinct()"to find out the different values and then use "count()"to count each of the values it's a stupid way to realize the result i want

Do you have any other ways ?

Zhao Tian
  • 3
  • 1
  • 4

2 Answers2

4

MongoEngine has some map reduce helpers that should meet your needs. The Queryset method item_frequencies[1] will meet your needs. There isnt any special support for the new aggregation framework but support could be added in the future.

Example usage:

BlogPost.objects.item_frequencies('tags')

[1] http://docs.mongoengine.org/en/latest/apireference.html?highlight=item_frequencies#mongoengine.queryset.QuerySet.item_frequencies

Ross
  • 17,861
  • 2
  • 55
  • 73
  • @Ross I find that we can only count all the frequency in a specific field,but what if I need to count the items in recent a few days or the nearest 10000 pieces of all the records? Do you have any idea? – Zhao Tian May 09 '13 at 09:16
  • item_frequencies is a map reduce job under the covers - so you can always drop to pymongo and create your own map reduce or aggregation. – Ross May 09 '13 at 09:44
1

MongoEngine itself has no special means to achieve this, but the MongoDB 2.2 aggregation framework lets you count documents, grouped by a field. I suggest using PyMongo's aggregate method directly with an aggregation pipeline to do this query:

http://api.mongodb.org/python/current/examples/aggregation.html

A. Jesse Jiryu Davis
  • 23,641
  • 4
  • 57
  • 70