• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:8 mins read
You are currently viewing MongoDB Get the Last N Records from the Collection?

How to get the last N records/documents from a MongoDB collection is the most used method. MongoDB has some methods to accomplish this task. I will create a collection student with five records inserted and I am going to retrieve the records by applying the appropriate method to get the last N records. The records in the collection student look like this:

Advertisements

# Create collection
db.student.insertMany([
      {
         "_id": 1,
         "name": "Larry Deol",
         "course": "Python"
      },
      {
         "_id": 2,
         "name": "Mark Steve",
         "course": "C++"
      },
      {
         "_id": 3,
         "name": "Caroline Candice",
         "course": "MongoDB"
      },
 {
         "_id": 4,
         "name": "Stephan Dark",
         "course": "Data Structure"
      },
 {
         "_id": 5,
         "name": "Anna James",
         "course": "Java"
      }
   ]
)

1. Using the Negative Index to Get the Last N Documents

The find() method in conjunction with the sort() and limit() methods are used to identify the last N records/documents from the MongoDB collection.

The sort() method sorts the collection in any order based on a field that represents the order of the records. Then, the limit() method limits the number of records returned to N.

In the following example, the find() method is used to retrieve all records from the student collection, and then the sort() method is used to sort the records in descending order as negative index -1 is assigned based on the field _id. Next, the amount of records returned is limited to “2” using the limit() method.  


# Using the negative index
db.student.find().sort({_id: -1}).limit(2)

The records from the last are displayed in the output here:

get last N records in mongodb

2. Using the skip() to Get the Last N Documents

Furthermore, we can use the skip() method to fetch the last N records from the collection. The skip() method drops the first N records from the collection. We need to provide value in the skip() method as an argument to tell MongoDB to skip a certain number of collections.

Consider the query, which retrieves the last N records from the collection student by using an index 3 with the skip() method. The toArray() method is used to convert the resulting cursor into an array.


# Using the skip() method 
db.student.find().skip(3).toArray();

As a result, we get the last two records only as the first three records are skipped by the skip() method.

get last N records in mongodb

More details about the $skip operator can be found here.

3. Using the skip() method with the count() Method

You can also use the skip() method along with the count() method of MongoDB to get last N records from the collection. The following query first counts the total number of records in the collection student using the $count method. It then uses the skip() method to skip over all but the last 2 records in the collection and returns the remaining records.


# Using the skip() method with the count() method 
db.student.find().skip(db.student.count() - 2)

The output obtained displayed the last two records of the collection by executing the above query.

get last N records from collection

4. Using the Aggregation Pipeline to Get the last N records in MongoDB

We may utilize the aggregation pipeline by using the $sort and $limit operators in the aggregate method. Putting these operators altogether in the following query, here the $sort operator sorts the records in descending order(-1) by the _id field and the $limit operator limits the number of records returned to 4. Then, the aggregate() method is used to execute the query.


# Using the aggregation pipeline
db.student.aggregate([
  { $sort: { _id: -1 } },
  { $limit: 4 }
]);

The last four records are yielded in the following output. 

5. Using the $natural Operator to Get Last N Documents

Alternatively, the $natural operator is also an approach to get a certain number of records from the given collection. There is no need to specify the field when using the $natural operator in the query. The following query uses the $natural operator inside the sort() method.

By default, MongoDB returns the three records in ascending order, so we use -1 to sort them in descending order here.


# Using the $natural operator 
db.student.find().sort({$natural: -1}).limit(3)

There, we got the output of the last three records inserted as the first three records by using the $natural operator.

get last N records in mongodb

6. Conclusion:

In general, retrieving the last N records from a MongoDB collection is a simple task that can be achieved by using the find(), sort(), and limit() methods. Conversely, the skip(), count(), and natural methods may be less efficient and slow for sorting large collections.

However, we can use all of the discussed methods to easily retrieve the data they need from their MongoDB collections.