-->

mongoengine +django how to count the number of ite

2019-09-08 20:39发布

问题:

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 ?

回答1:

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



回答2:

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