Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo - querying most recent N items

Tags:

python

pymongo

What is the 'proper way' to retrieve most recent N items from the database?

from tutorial and mongodb documentations it seems (besides using range queries)

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

is it right?

like image 227
thkang Avatar asked Dec 06 '25 08:12

thkang


1 Answers

Your syntax doesn't really seem quite right there.

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

Should do what you would expect.

Python and pymongo support simple chaining.


NOTE
Sorting on _id does not necessarily yield the "most recent" item.

like image 103
Randall Hunt Avatar answered Dec 08 '25 20:12

Randall Hunt