WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

MongoDB · Basic · question 13 of 100

How do you sort and limit the results of a query in MongoDB?

📕 Buy this interview preparation book: 100 MongoDB questions & answers — PDF + EPUB for $5

Sorting and limiting the results of a query are common operations in MongoDB, and they are achieved by using the ‘sort‘ and ‘limit‘ methods respectively.

To sort the results of a query, you can use the ‘sort‘ method to specify one or more fields to sort by, and the sort order for each field (either ascending or descending). For example, to sort a collection of products by their prices in descending order, you can use the following query:

db.products.find().sort({ price: -1 })

This query sorts the results of the ‘find()‘ method by the ‘price‘ field in descending order (-1).

To limit the number of results returned by a query, you can use the ‘limit‘ method to specify the maximum number of documents to return. For example, to limit the number of documents returned by the previous query to 10, you can use the following query:

db.products.find().sort({ price: -1 }).limit(10)

This query returns the first 10 documents sorted by the ‘price‘ field in descending order.

It is also possible to combine the ‘sort‘ and ‘limit‘ methods in a single query to retrieve a sorted and limited subset of documents. For example, to retrieve the 10 most expensive products in the collection, you can use the following query:

db.products.find().sort({ price: -1 }).limit(10)

This query sorts the documents by their ‘price‘ field in descending order and returns the first 10 documents in the sorted list.

It is important to note that the ‘sort‘ and ‘limit‘ methods should be used in conjunction with an appropriate index to avoid querying the entire collection and causing performance issues. For example, to optimize the query above, you could create an index on the ‘price‘ field.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic MongoDB interview — then scores it.
📞 Practice MongoDB — free 15 min
📕 Buy this interview preparation book: 100 MongoDB questions & answers — PDF + EPUB for $5

All 100 MongoDB questions · All topics