Skip to main content

๐Ÿ‘ ORDER BY โ†’ .sort() & LIMIT โ†’ .limit()

In SQL, we use ORDER BY to sort query results and LIMIT to restrict the number of returned rows. MongoDB provides the .sort() and .limit() methods to achieve the same.


Sorting in MongoDBโ€‹

  • { field: 1 } โ†’ Ascending order (A โ†’ Z, smallest to largest)
  • { field: -1 } โ†’ Descending order (Z โ†’ A, largest to smallest)
  • You can sort by multiple fields, just like SQL.

Limiting resultsโ€‹

  • .limit(n) restricts the number of documents returned.
  • Used together with .sort(), it helps fetch the top N results.

1: Top 5 books with the highest inventoryโ€‹

db.books.find().sort({ totalInventory: -1 }).limit(5);

Equivalent SQL query:

SELECT * FROM books ORDER BY totalInventory DESC LIMIT 5;

This fetches the 5 books with the highest stock.


2: Get the title of top 10 fiction books by highest page countโ€‹

db.books
.find({ genres: "Fiction" }, { title: 1, pages: 1 })
.sort({ pages: -1 })
.limit(10);
info

Along with the title, we fetched pages, as well, to ensure that we are getting the right results.

Equivalent SQL query:

SELECT title, pages FROM books WHERE genres='Fiction' ORDER BY pages DESC LIMIT 10;

This returns the top 10 available books in the "Science Fiction" genre.


Challengeโ€‹

๐Ÿ‘ 1. Find the first 10 books alphabetically by title.โ€‹

Answer
  db.books.find({}).sort({title: 1}).limit(10)