34

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

user235925
  • 838
  • 1
  • 8
  • 11

1 Answers1

77

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')
bagerard
  • 5,681
  • 3
  • 24
  • 48
dcrosta
  • 26,009
  • 8
  • 71
  • 83
  • 4
    Thanks, great answer! for whatever reason I couldn't find that in the docs – user235925 Sep 06 '11 at 16:03
  • 1
    `order_by` link update: http://docs.mongoengine.org/en/latest/apireference.html?highlight=order_by#mongoengine.queryset.QuerySet.order_by – tester Nov 08 '13 at 08:25
  • Good answer but the link is broken – Andres Apr 24 '14 at 19:27
  • 5
    In the last line of the example, `Person.objects` must be `Person.objects()` – TimeEmit May 21 '15 at 22:39
  • You have not specified the web framework you are using. In case it is Django, you can use the Django ORM directly with Mongodb instead of using Mongoengine by using the [djongo connection](https://nesdis.github.io/djongo/) – nesdis Jan 03 '18 at 14:42
  • 1
    http://docs.mongoengine.org/apireference.html#mongoengine.queryset.QuerySet.order_by – technazi Jun 06 '19 at 21:17
  • Also, use '-' for descending and '+' for ascending: something like ``Post.objects.order_by("-created_date")`` would return the entries with most recent first. – atultw Mar 07 '21 at 19:52