Pymongo - Query the most recent N items

What is the "correct way" to fetch the latest items from the database?

from the mongodb tutorial and documentation it seems (besides range queries)

db.collection.find(skip = 0, limit=N, sort=[("_id", -1)])

Is it correct?

+3


source to share


1 answer


Your syntax is actually not quite right.

db.collection.find({}).sort("_id", -1).limit(N)

      

Should do what you expect.



Python and pymongo support simple chaining.


Note
Sorting by _id

does not necessarily result in the "last" item.

+5


source







All Articles