Projection, Sorting, Limit & Skip
10 min read
Shaping and Paginating Results
Projection controls which fields are returned. Sort orders the results. Limit caps the number of documents returned. Skip offsets the starting point — together, limit and skip enable pagination.
Projection
js
// Return only name and course; exclude _id
db.students.find({}, { name: 1, course: 1, _id: 0 });Sort, Limit, Skip
js
// Sort by age descending, return first 5
db.students.find({}).sort({ age: -1 }).limit(5);
// Page 2 of 5 results per page
const page = 2;
const pageSize = 5;
db.students.find({}).skip((page - 1) * pageSize).limit(pageSize);Use 1 to include a field and 0 to exclude it. You cannot mix inclusions and exclusions except for _id.
Ready to test yourself?
Practice MongoDB— quiz & coding exercises