I can’t find anywhere it has been documented this. By default, the find() operation will get the records from beginning. How can I get the last N records in mongodb?
Edit: also I want the returned result ordered from less recent to most recent, not the reverse.
If I understand your question, you need to sort in ascending order.
Assuming you have some id or date field called “x” you would do …
.sort()
The 1 will sort ascending (oldest to newest) and -1 will sort descending (newest to oldest.)
If you use the auto created _id field it has a date embedded in it … so you can use that to order by …
That will return back all your documents sorted from oldest to newest.
Natural Order
You can also use a Natural Order mentioned above …
Again, using 1 or -1 depending on the order you want.
Use .limit()
Lastly, it’s good practice to add a limit when doing this sort of wide open query so you could do either …
or