MongoDB query to skip n first documents?


To skip a specific number of documents, use skip() along with limit. Let us create a collection with documents −

> db.demo246.insertOne({"StudentFirstName":"Chris","StudentLastName":"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b0d71627c0c63e7dba65")
}
> db.demo246.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b0e21627c0c63e7dba66")
}
> db.demo246.insertOne({"StudentFirstName":"John","StudentLastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b0ea1627c0c63e7dba67")
}
> db.demo246.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b0f91627c0c63e7dba68")
}

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

> db.demo246.find();

This will produce the following output −

{ "_id" : ObjectId("5e46b0d71627c0c63e7dba65"), "StudentFirstName" : "Chris", "StudentLastName" : "Brown" }
{ "_id" : ObjectId("5e46b0e21627c0c63e7dba66"), "StudentFirstName" : "John", "StudentLastName" : "Doe" }
{ "_id" : ObjectId("5e46b0ea1627c0c63e7dba67"), "StudentFirstName" : "John", "StudentLastName" : "Smith" }
{ "_id" : ObjectId("5e46b0f91627c0c63e7dba68"), "StudentFirstName" : "Carol", "StudentLastName" : "Taylor" }

Following is the query in MongoDB to skip n first documents −

> db.demo246.find().skip(2).limit(1);

This will produce the following output −

{ "_id" : ObjectId("5e46b0ea1627c0c63e7dba67"), "StudentFirstName" : "John", "StudentLastName" : "Smith" }

Updated on: 30-Mar-2020

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements