MongoDB query to skip first 5 records and display only the last 5 of them

To skip records in MongoDB, use skip(). With that, to display only a specific number of records, use limit().

Syntax

db.collection.find().skip(numberOfRecordsToSkip).limit(numberOfRecordsToDisplay);

Create Sample Data

Let us create a collection with documents ?

db.demo275.insertMany([
    {"Number": 10},
    {"Number": 12},
    {"Number": 6},
    {"Number": 1},
    {"Number": 5},
    {"Number": 24},
    {"Number": 8},
    {"Number": 9},
    {"Number": 19},
    {"Number": 29}
]);
{
  "acknowledged": true,
  "insertedIds": [
    ObjectId("5e48eac4dd099650a5401a43"),
    ObjectId("5e48eac7dd099650a5401a44"),
    ObjectId("5e48eac9dd099650a5401a45"),
    ObjectId("5e48eacadd099650a5401a46"),
    ObjectId("5e48eacddd099650a5401a47"),
    ObjectId("5e48ead0dd099650a5401a48"),
    ObjectId("5e48ead6dd099650a5401a49"),
    ObjectId("5e48ead8dd099650a5401a4a"),
    ObjectId("5e48eadddd099650a5401a4b"),
    ObjectId("5e48eae1dd099650a5401a4c")
  ]
}

Display all documents from a collection with the help of find() method ?

db.demo275.find();
{ "_id" : ObjectId("5e48eac4dd099650a5401a43"), "Number" : 10 }
{ "_id" : ObjectId("5e48eac7dd099650a5401a44"), "Number" : 12 }
{ "_id" : ObjectId("5e48eac9dd099650a5401a45"), "Number" : 6 }
{ "_id" : ObjectId("5e48eacadd099650a5401a46"), "Number" : 1 }
{ "_id" : ObjectId("5e48eacddd099650a5401a47"), "Number" : 5 }
{ "_id" : ObjectId("5e48ead0dd099650a5401a48"), "Number" : 24 }
{ "_id" : ObjectId("5e48ead6dd099650a5401a49"), "Number" : 8 }
{ "_id" : ObjectId("5e48ead8dd099650a5401a4a"), "Number" : 9 }
{ "_id" : ObjectId("5e48eadddd099650a5401a4b"), "Number" : 19 }
{ "_id" : ObjectId("5e48eae1dd099650a5401a4c"), "Number" : 29 }

Example: Skip First 5 Records and Display Next 5

Following is the query to skip first 5 records and display only the last 5 of them ?

db.demo275.find().skip(5).limit(5);
{ "_id" : ObjectId("5e48ead0dd099650a5401a48"), "Number" : 24 }
{ "_id" : ObjectId("5e48ead6dd099650a5401a49"), "Number" : 8 }
{ "_id" : ObjectId("5e48ead8dd099650a5401a4a"), "Number" : 9 }
{ "_id" : ObjectId("5e48eadddd099650a5401a4b"), "Number" : 19 }
{ "_id" : ObjectId("5e48eae1dd099650a5401a4c"), "Number" : 29 }

How It Works

The skip(5) method skips the first 5 documents, and limit(5) restricts the result to the next 5 documents. This combination is useful for pagination and retrieving specific subsets of data.

Conclusion

Combine skip() and limit() to retrieve specific ranges of documents from MongoDB collections. This method is particularly useful for implementing pagination in applications.

Updated on: 2026-03-15T02:16:25+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements