MongoDB Aggregation $match
Introduction
The $match
stage in MongoDB's aggregation framework is used to filter documents based on specified criteria. It is similar to the find
operation in MongoDB but is used within the context of an aggregation pipeline. The $match
stage helps you narrow down the dataset before further processing, making your aggregation queries more efficient.
Prerequisites
MongoDB installed and running on your machine.
Access to
mongosh
and a populated database with sample data.
Step 1: Start mongosh
mongosh
Open Terminal/Command Prompt:
Launch your terminal (macOS/Linux) or command prompt (Windows).
Start
mongosh
:Type the following command and press Enter:
Step 2: Switch to the Database
Switch to the database where your collection is located.
Use a Database:
Step 3: Sample Data
Let’s assume you have a collection named sales
with documents that look like this:
Step 4: Using $match
$match
1. Basic Usage of $match
$match
To filter documents based on a specific condition, you can use the $match
stage. For example, if you want to find all items in the fruit
category:
Output:
2. Using Comparison Operators
You can use various comparison operators in the $match
stage. For example, to find items with a quantity greater than 5:
Output:
3. Using Logical Operators
Logical operators like $and
, $or
, and $not
can be used to combine multiple conditions. For example, to find items that are either in the fruit
category or have a price less than 2:
Output:
4. Combining $match
with Other Stages
$match
with Other StagesThe $match
stage can be combined with other aggregation stages for more complex queries. For example, if you want to find items in the fruit
category and then sort them by price
:
Output:
Conclusion
You have learned how to use the $match
stage in MongoDB's aggregation framework to filter documents based on specified criteria. The $match
stage is essential for refining your dataset and can be used in combination with other stages to create complex aggregation queries.
Feel free to reach out if you have any questions or need further guidance!
Last updated