In MongoDB, skip() method is used to skip the documents from the collection.
We can use the skip method to implement pagination logic.
Syntax:-
db.collectionName.find().skip(numberOfDocument);
Suppose, you have employees collection and it has 5 documents
[
{
"_id" : ObjectId("5f26e736deec6e20ea057831"),
"name" : "John",
"age" : 35,
"department" : "department A",
"salary" : 200000
},
{
"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
"name" : "Rom",
"age" : 30,
"department" : "department A",
"salary" : 70000
},
{
"_id" : ObjectId("5f26e9dedeec6e20ea057833"),
"name" : "Tony",
"age" : 31,
"department" : "department B",
"salary" : 40000
},
{
"_id" : ObjectId("5f26e9dedeec6e20ea057834"),
"name" : "Peter",
"age" : 32,
"department" : "department B",
"salary" : 30000
},
{
"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
"name" : "Andrew",
"age" : 33,
"department" : "department C",
"salary" : 20000
}
]
Now, you want to get the documents which are starting from the 3rd document.
> db.employees.find().skip(2).toArray();
Output:-
[
{
"_id" : ObjectId("5f26e9dedeec6e20ea057833"),
"name" : "Tony",
"age" : 31,
"department" : "department B",
"salary" : 40000
},
{
"_id" : ObjectId("5f26e9dedeec6e20ea057834"),
"name" : "Peter",
"age" : 32,
"department" : "department B",
"salary" : 30000
},
{
"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
"name" : "Andrew",
"age" : 33,
"department" : "department C",
"salary" : 20000
}
]
MongoDB skip() method – Interview Questions
Q 1: What does skip() do?
Ans: It skips a specified number of documents.
Q 2: Where is skip() commonly used?
Ans: Pagination.
Q 3: Can skip() be combined with limit()?
Ans: Yes
Q 4: Does skip() affect performance?
Ans: Yes, large skip values reduce performance.
Q 5: Syntax of skip()?
Ans: db.collection.find().skip(number).