Sort and Limit MongoDB Results

MongoDBBeginner
Practice Now

Introduction

In this lab, you will learn fundamental MongoDB querying techniques for sorting, limiting, and filtering database results. These skills are essential for managing and retrieving data efficiently. You will work with the MongoDB shell (mongosh) to perform these operations on a sample collection of documents.

The lab will guide you through sorting documents by single or multiple fields, controlling the number of results returned using limits and offsets, and counting documents that match specific criteria. By the end of this lab, you will have a solid understanding of how to organize and retrieve data from a MongoDB database.

Sort Documents by a Single Field

In this step, you will learn how to sort documents in a MongoDB collection. Sorting allows you to organize query results in a specific order, which is crucial for data analysis and presentation. Your environment has been pre-configured with a bookstore database containing a books collection.

First, open the MongoDB shell to interact with the database. In your terminal, run the following command:

mongosh

Once inside the shell, switch to the bookstore database.

use bookstore

To see the documents in the books collection, you can use the find() method.

db.books.find();

Now, let's sort these documents. To sort by a single field, you chain the .sort() method to a find() query. The sort() method takes an object specifying the field to sort by and the direction: 1 for ascending and -1 for descending.

Let's sort the books by the number of pages in ascending order (from fewest to most pages).

db.books.find().sort({ pages: 1 });

You will see the book with the fewest pages, "Python Basics", listed first.

[
  {
    _id: ObjectId('...'),
    title: 'Python Basics',
    pages: 250,
    price: 29.99
  },
  {
    _id: ObjectId('...'),
    title: 'MongoDB Fundamentals',
    pages: 300,
    price: 34.99
  },
  ...
]

Next, let's sort the books by price in descending order to find the most expensive ones first.

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

This command will display "Data Science" at the top, as it has the highest price.

[
  {
    _id: ObjectId('...'),
    title: 'Data Science',
    pages: 350,
    price: 44.99
  },
  {
    _id: ObjectId('...'),
    title: 'JavaScript Advanced',
    pages: 400,
    price: 39.99
  },
  ...
]

Sort by Multiple Fields

Sometimes, sorting by a single field is not enough. MongoDB allows you to specify multiple keys for sorting to create more refined orderings. In this step, you will learn how to sort documents based on a sequence of fields.

Let's add a few more books to our collection to better illustrate multi-key sorting. These new books share the same price as an existing one but have different page counts.

db.books.insertMany([
  { title: "Machine Learning", pages: 420, price: 39.99 },
  { title: "Web Development", pages: 380, price: 39.99 }
]);

Now, we have three books priced at $39.99. If we sort by price alone, the order of these three books is not guaranteed. To create a predictable order, we can add a second sort key.

Let's sort the books first by price in ascending order, and then by pages in descending order for books with the same price.

db.books.find().sort({ price: 1, pages: -1 });

The query processor first sorts all documents by price. Then, for documents that have the same price (like our three books at $39.99), it sorts them by pages in descending order.

Your output for the $39.99 books should appear in this order:

  1. "Machine Learning" (420 pages)
  2. "JavaScript Advanced" (400 pages)
  3. "Web Development" (380 pages)
[
  ...,
  {
    _id: ObjectId('...'),
    title: 'Machine Learning',
    pages: 420,
    price: 39.99
  },
  {
    _id: ObjectId('...'),
    title: 'JavaScript Advanced',
    pages: 400,
    price: 39.99
  },
  {
    _id: ObjectId('...'),
    title: 'Web Development',
    pages: 380,
    price: 39.99
  },
  ...
]

This technique is useful for creating complex, stable sorting for user interfaces and reports.

Limit and Skip Results

When working with large datasets, you often need to retrieve only a subset of the results. MongoDB provides the .limit() and .skip() methods for this purpose. Together, they are the foundation for implementing pagination.

The .limit() method restricts the number of documents returned by a query. Let's retrieve only the top 3 most expensive books.

db.books.find().sort({ price: -1 }).limit(3);

This command first sorts all books by price in descending order and then returns only the first three documents from the sorted list.

The .skip() method tells the cursor to ignore a specified number of documents at the beginning of the result set. This is useful for navigating through pages of data.

For example, to get the second page of results where each page has 2 books, you would skip the first 2 books and limit the result to 2. Let's apply this to our price-sorted list to get the 3rd and 4th most expensive books.

db.books.find().sort({ price: -1 }).skip(2).limit(2);

This query performs the following actions in order:

  1. sort({ price: -1 }): Sorts all books from most to least expensive.
  2. skip(2): Skips the top 2 most expensive books.
  3. limit(2): Returns the next 2 books from the list.

The output will show the third and fourth books in the sorted list.

[
  {
    _id: ObjectId('...'),
    title: 'JavaScript Advanced',
    pages: 400,
    price: 39.99
  },
  {
    _id: ObjectId('...'),
    title: 'Web Development',
    pages: 380,
    price: 39.99
  }
]

By adjusting the values in skip() and limit(), you can implement a complete pagination system.

Count Documents

Another common requirement is to count the number of documents in a collection, either in total or matching a specific filter. MongoDB provides the countDocuments() method for this.

To get the total number of books in our collection, run the following command:

db.books.countDocuments();

This will return the total count of documents, which should be 6 after the additions from Step 2.

More powerfully, countDocuments() can accept a query filter to count only the documents that match certain criteria. Let's count how many books cost more than 35. We use the `gt` (greater than) query operator for this.

db.books.countDocuments({ price: { $gt: 35 } });

This will return the number of books whose price is greater than 35.

You can also use multiple conditions in your filter. Let's count the books that are priced at exactly $39.99 and have 400 or more pages. We use the $gte (greater than or equal to) operator here.

db.books.countDocuments({ price: 39.99, pages: { $gte: 400 } });

This command will return 2, corresponding to "Machine Learning" (420 pages) and "JavaScript Advanced" (400 pages). Using countDocuments() with filters is an efficient way to get statistics about your data without retrieving the documents themselves.

To exit the MongoDB shell, you can type exit or press Ctrl+D.

exit;

Summary

In this lab, you have learned several essential MongoDB querying techniques. You started by sorting documents using a single field in both ascending and descending order with the .sort() method. You then advanced to multi-key sorting, which allows for more complex and stable ordering of results.

Next, you explored how to control the size of your result set using .limit() to restrict the number of documents returned and .skip() to implement pagination. Finally, you learned how to use countDocuments() to efficiently count documents, both in an entire collection and those matching specific filter criteria. These commands are fundamental tools for any developer working with MongoDB.