Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort using MongoEngine?

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

like image 493
user235925 Avatar asked Sep 06 '11 06:09

user235925


People also ask

How do you query in MongoEngine?

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.

How do I sort in MongoDB?

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.

Should I use PyMongo or MongoEngine?

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.

How do I sort data in PyMongo?

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.


1 Answers

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') 
like image 193
dcrosta Avatar answered Sep 21 '22 15:09

dcrosta