mongoengine +django how to count the number of items of same content

让人想犯罪 __ 提交于 2020-01-16 12:24:07

问题


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



来源:https://stackoverflow.com/questions/13468687/mongoengine-django-how-to-count-the-number-of-items-of-same-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!