Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / Sorting Limiting Pagination
interview

Q1. How do you sort query results in MongoDB?
Use the sort() method on a cursor. Specify field and direction (1 for ascending, -1 for descending):
db.users.find().sort({ age: 1, name: -1 })
You can also use
.sort({ age: -1 })
for descending.

Q2. How do you limit the number of results?
Use limit() to restrict the number of documents returned:
db.users.find().limit(5)
This is useful for pagination and for retrieving only the top N records.

Q3. How do you skip documents for pagination?
Use skip() to ignore a specified number of documents:
db.users.find().skip(10).limit(5)
This skips the first 10 and returns the next 5. Combined with sort, this enables pagination (e.g., page 3 with 5 per page: skip(10), limit(5)).

Q4. What are the performance considerations with skip and limit?
Using skip with large values can be inefficient because MongoDB still scans through all skipped documents. For large datasets, consider using range-based pagination with filters (e.g.,
find({ _id: { $gt: lastSeenId } }).limit(10)
).

Q5. How do you get a random sample of documents?
Use the aggregation framework's $sample stage:
db.users.aggregate([ { $sample: { size: 3 } } ])
This returns 3 random documents from the collection. Note that $sample may scan the collection for large sizes.