How to get the last N records in mongodb

We can use various approaches to get the last n record from database. Let find out which approach suits you.

You can use combination of the  sort() , limit() ,skip() to get the last N record from the database.

Solution 1

If you have some field on that basis you want to sort, then get last N records

db.collection.find().sort(field:1).limit(N)

The 1 will sort ascending order and -1 will sort descending descending order.

Example:

db.collection.find().sort(_id:1).limit(100)

The above query will give you last 100 records since we sorted the records on the basis of _id (oldest to newest)

Solution 2

If we want sort on the basis of natural order, means the oder in which document inserted into disk. For this purpose we can use $natural

The order in which the database refers to documents on disk. This is the default sort order. See $natural and Return in Natural Order.

natural order
db.collection.find().sort({$natural:1}).limit(N);

using 1 or -1 depending on the order you want.

Solution 3

The last N added records, from less recent to most recent, can be seen with this query:

db.collection.find().skip(db.collection.count() - N)

Solution 4

n order to get last N records you can execute below query:

db.collection.find({$query: {}, $orderby: {$natural : -1}}).limit(N)

Note: In place of $natural you can use one of the columns from your collection.

Solution 6

Using aggregation pipeline, we can achieve this also

db.collection.aggregation([
    {
        "$match": { //stage 1: filter out a subset
        }
    },
    {
        "$sort": { //stage 2: sort the remainder last-first
        }
    },
    {
        "$limit": N //stage 3: keep only N of the descending order subset
    },
    {
        "$sort": {
            //stage 4: sort back the above result to ascending order
        }
    },
    {
        "$project": { //stage 5: add any fields you want to show in your results
        }
    }
])

Leave a Reply