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.
You may want to be using the
find
options : http://docs.meteor.com/api/collections.html#Mongo-Collection-findThe last N added records, from less recent to most recent, can be seen with this query:
If you want them in the reverse order:
If you install Mongo-Hacker you can also use:
If you get tired of writing these commands all the time you can create custom functions in your ~/.mongorc.js. E.g.
then from a mongo shell just type
last(N)
you can use
sort()
,limit()
,skip()
to get last N record start from any skipped valueLast function should be
sort
, notlimit
.Example:
@bin-chen,
You can use an aggregation for the latest n entries of a subset of documents in a collection. Here's a simplified example without grouping (which you would be doing between stages 4 and 5 in this case).
This returns the latest 20 entries (based on a field called "timestamp"), sorted ascending. It then projects each documents _id, timestamp and whatever_field_you_want_to_show into the results.
so, result would look something like:
Hope this helps.
In order to get last N records you can execute below query:
if you want only one last record:
Note: In place of $natural you can use one of the columns from your collection.