pymongo sorting by date

Question:

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?

Asked By: Emmet B

||

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)
]):
Answered By: Lix

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

db.posts.find().sort('date', -1)
Answered By: Arkadiusz Choczaj

I do something like this in Flask and PyMongo.

import datetime

the sort function:

def sort_data_by_dates(data):
    return datetime.strptime(data['created'], '%d-%m-%Y %I:%M')

the actual view and function:

@app.route("/data", methods=["POST", "GET"])
def get_data:
    data = list(db.posts.find())
    sorted_data = sorted(data, key=sort_prospect_by_dates, reverse=True)
Answered By: dadevfa
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.