Storing and retrieving data alone isn’t enough for production systems. Users often need to search, filter, and organize data based on specific conditions. For example, an e-commerce application may allow users to filter products by price or sort them by popularity. Without filtering and sorting, applications would return large, unorganized datasets that are difficult to use.
This is where filtering and sorting in MongoDB APIs become essential. They let you query only the required data and return it in a defined order. In this tutorial, we will start from the basics and learn how filtering and sorting work in MongoDB. Then we will implement them step by step in a Node.js API using Express and Mongoose. By the end, you will be able to build APIs that handle real-world querying scenarios efficiently.
Understanding Filtering
Filtering is the process of retrieving only those records that match certain conditions. Instead of returning all documents from a collection, you define criteria that the data must satisfy. For example, in a user’s collection, filtering lets you retrieve records above a certain age or with a specific email. This improves performance and keeps API responses relevant.
In MongoDB, filtering is done using query objects. These objects define conditions in key-value form, which MongoDB uses to match documents.

Understanding Sorting
Sorting is the process of arranging data in a specific order. Once you retrieve filtered data, you often want to display it in a meaningful sequence, such as newest first or alphabetically.
In MongoDB, sorting is handled using the sort() method. You can sort data in ascending or descending order based on one or more fields.
Sorting is important because it enhances user experience. For example, users often expect to see the most recent or most relevant data first.

Project Structure
Before implementing filtering and sorting, it is important to organize the project in a scalable way. A clean structure ensures that database logic, business logic, and routing are separated.
This structure allows you to implement filtering and sorting logic in a maintainable way.
Step 1: Set Up the Database Connection
To begin, the database connection is defined inside the src/config/db.js file. This file ensures that your application connects to MongoDB before handling any requests.
This setup keeps database configuration isolated from the rest of the application.
Step 2: Create the Product Model
To demonstrate filtering and sorting, we define a product schema inside the src/models/product.model.js file. This model represents the data stored in MongoDB.
This model will allow us to filter products by category or price and sort them accordingly.
Step 3: Implement Filtering and Sorting Logic
Move filtering and sorting logic from controllers into the service layer. Inside the src/services/product.service.js file, we define a function that dynamically builds queries based on user input.
This approach allows the API to dynamically filter and sort data based on query parameters.
Step 4: Create a Controller
The controller receives incoming requests and passes parameters to the service layer. Inside the src/controllers/product.controller.js file, we extract query parameters and return the result.
This keeps the controller clean and focused on request handling.
Step 5: Define Routes
Routes define how API endpoints are exposed. Inside the src/routes/product.routes.js file, we connect the route to the controller.
This allows users to access filtering and sorting through API requests.
Step 6: Set Up the Express Application
The Express application is configured inside the src/app.js file, where routes are registered.
This connects the API endpoint to the application.

Step 7: Start the Server
The server.js file acts as the entry point of the application. It initializes the database connection and starts the server.
Once the server is running, the API is ready to handle requests.
Real-World Example
You can now test your API using query parameters.
For example, to filter products by category and price range, you can send a request like:
To sort products by price in descending order:
You can also combine filtering and sorting:
This flexibility allows your API to handle real-world use cases.

Handling Edge Cases
In real-world applications, users may provide invalid or missing query parameters. It is important to validate inputs before using them.
For example, you should ensure that price values are numbers and that sorting fields are valid. This prevents unexpected errors and improves API reliability.
You can also set default values when parameters are not provided, ensuring consistent behavior.
Production Considerations
While this implementation works well for basic use cases, production systems require additional improvements. You should consider adding pagination to limit results, indexing fields for faster queries, and validating input using libraries such as Joi or Zod.
These enhancements ensure that your API remains efficient and scalable as data grows.

Conclusion
In this tutorial, we explored how to filter and sort data in MongoDB using a Node.js API. We started with the basic concepts of filtering and sorting, then implemented a scalable solution using a clean architecture.
Filtering and sorting are core features in most APIs. With a well-structured API and dynamic query handling, you can build flexible and efficient systems.