MongoDB query to skip n first documents?

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 30-Mar-2020 17:18:19
Advertisements