Pymongo sort by date

First I want to receive new messages and try the following:

db.posts.find({"date": {"$lt": tomorrow, "$gte": today}}).sort({'date':pymongo.DESCENDING}) 

(without sorting , I get the oldest messages first)

I get this error

 TypeError: if no direction is specified, key_or_list must be an instance of list 

What's going on here? Can't sort by date?

+5
source share
2 answers

This is not a valid parameter format for the sort function. The correct syntax would look something like this:

 db.posts.find(...).sort('date',pymongo.DESCENDING) 

Here is a link to the relevant documentation for the sort function: http://api.mongodb.org/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor.sort

You can use the following syntax to sort by several parameters:

 db.posts.find(...).sort([ ('date', pymongo.ASCENDING), ('other_field', pymongo.DESCENDING) ]): 
+12
source

In PyMongo, you can also try this if there is an error for .sort ('date', pymongo.DESCENDING)

 db.posts.find().sort('date', -1) 
+3
source

All Articles