codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

MongoDB

15 / 65 topics
12Querying Basics13Find Queries14Projection15Sorting and Limiting16Aggregation Framework17Operators in MongoDB18Text Search
Tutorials/MongoDB/Sorting and Limiting
🍃MongoDB

Sorting and Limiting

Updated 2026-04-20
3 min read

Sorting and Limiting in MongoDB

Introduction

Sorting and limiting are essential operations when working with large datasets in MongoDB. They allow you to retrieve data in a specific order and control the number of documents returned, which can significantly improve performance and usability. In this section, we will explore how to use sorting and limiting effectively in your MongoDB queries.

Sorting Data

Overview

Sorting allows you to organize the retrieved documents based on one or more fields. This is particularly useful when you need to display data in a specific order, such as alphabetical order, numerical order, or by date.

Basic Syntax

The basic syntax for sorting in MongoDB is:

db.collection.find().sort({ field1: order1, field2: order2, ... })
  • field: The name of the field to sort by.
  • order: The sort order. Use 1 for ascending and -1 for descending.

Example

Suppose you have a collection named products with documents containing fields like name, price, and category. To retrieve all products sorted by price in ascending order, use the following query:

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

To sort by multiple fields, such as category first and then name within each category, you can do:

db.products.find().sort({ category: 1, name: 1 })

Best Practices

  • Indexing: Ensure that the fields used in sorting are indexed to improve performance. MongoDB uses indexes to speed up sort operations.

  • Limit Fields: When sorting large datasets, consider limiting the number of fields returned using the projection method to reduce memory usage.

Limiting Data

Overview

Limiting allows you to restrict the number of documents returned by a query. This is useful for pagination or when you only need a subset of data.

Basic Syntax

The basic syntax for limiting in MongoDB is:

db.collection.find().limit(number)
  • number: The maximum number of documents to return.

Example

To retrieve the first 10 products sorted by price, use the following query:

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

This is particularly useful for implementing pagination in applications. For example, to get the second page of results with a page size of 10, you can combine skip and limit:

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

Best Practices

  • Skip Usage: Be cautious when using skip for pagination, especially with large datasets. It can become inefficient as the number of documents skipped increases.

  • Batch Size: Consider using batch size in your application logic to handle large result sets more efficiently.

Combining Sorting and Limiting

You can combine sorting and limiting to refine your queries further. This is common in scenarios where you need a specific subset of sorted data.

Example

To retrieve the top 5 most expensive products, use:

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

This query first sorts all products by price in descending order and then limits the result to the top 5 documents.

Advanced Sorting Techniques

Text Indexes

MongoDB supports sorting on text indexes. This is useful when you need to sort documents based on full-text search results.

Example

To create a text index on the description field:

db.products.createIndex({ description: "text" })

Then, perform a text search and sort by score:

db.products.find({ $text: { $search: "electronics" } }).sort({ score: { $meta: "textScore" } })

Compound Indexes

Compound indexes can be used to optimize sorting on multiple fields. They improve performance by reducing the number of documents that need to be examined.

Example

To create a compound index on category and price:

db.products.createIndex({ category: 1, price: -1 })

This index will speed up queries that sort by these two fields together.

Conclusion

Sorting and limiting are powerful features in MongoDB that help you manage and present data effectively. By understanding how to use them correctly, you can optimize your database operations and improve the performance of your applications. Always consider indexing, best practices for pagination, and advanced sorting techniques to get the most out of these functionalities.


PreviousProjectionNext Aggregation Framework

Recommended Gear

ProjectionAggregation Framework