Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo sorting by date

I want to get newest posts first, and try the following:

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

(without sort, I get the oldest posts first fine)

I am getting this error

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

What is going on here? Is not it possible to sort by date?

like image 977
Emmet B Avatar asked Jun 04 '15 11:06

Emmet B


People also ask

How do I sort by date in MongoDB?

In MongoDB, you have to use the sort() method for sort by date using an array. In the sort() method you have to specify the date field by which you want to sort and direction (ascending or descending order). Here, the student is the collection name and for inserting the date we use the ISODate() function.

Does MongoDB support sorting?

MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted. The sort keys must be listed in the same order as defined in the index.

How do I sort fields 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.

What is the use of sort () in MongoDB?

This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field.


1 Answers

This is not the correct format of parameters 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

To sort by multiple parameters you can use the following syntax:

db.posts.find(...).sort([
  ('date', pymongo.ASCENDING),
  ('other_field', pymongo.DESCENDING)
]):
like image 153
Lix Avatar answered Oct 03 '22 19:10

Lix