How do I sort the query objects in MongoEngine, like I would in a regular mongodb query?
http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order
The connect() function returns a MongoClient object. Using list_database_names() method available to this object, we can retrieve number of databases on the server. It is also possible to obtain list of collections in a database, using list_collection_names() method.
To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.
Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.
To sort the results of a query in ascending or, descending order pymongo provides the sort() method. To this method, pass a number value representing the number of documents you need in the result.
Mongoengine is inspired by Django's ORM, and like Django, it uses order_by
to sort the result set. order_by
takes a variable number of string arguments, which are the field names (as defined in your documents) optionally preceded by a "-
" (to indicate a descending sort, i.e. highest first).
For example:
class Person(Document): first_name = StringField() last_name = StringField() age = IntField() # later people = Person.objects.order_by('last_name', '-age')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With