$match Stage in MongoDB Aggregation Pipeline
1. Definition
The $match stage is used to filter documents in an aggregation pipeline. It selects only those documents that match specific conditions.
2. Simple Understanding
👉 It works like find() in MongoDB
👉 It filters data before passing it to the next stage
3. When to Use
- When filtering data in aggregation
- Before grouping or sorting
- To reduce dataset size early
- When applying conditions on fields
4. Where it is Used
- Aggregation pipelines
- Data filtering operations
- Analytics and reporting queries
- Backend APIs
5. Why We Use It
- Reduces unnecessary data processing
- Improves performance
- Filters relevant documents early
- Works with indexes for optimization
6. How It Works
- Applies filtering conditions
- Only matching documents move to next stage
- Similar syntax to query operators
- Can use operators like $gt, $lt, $eq
7. Basic Syntax
db.collection.aggregate([
{ $match: { age: { $gt: 20 } } }
]);8. Real Example
// Get users with role Developer
db.users.aggregate([
{ $match: { role: "Developer" } }
]);
// Get users older than 25
db.users.aggregate([
{ $match: { age: { $gt: 25 } } }
]);9. Explanation
- $match filters documents
- Works like find() query
- Reduces data early in pipeline
- Improves overall pipeline performance
10. Advantages
- Fast filtering
- Works with indexes
- Improves pipeline efficiency
- Easy to use
11. Disadvantages
- Must be placed correctly for best performance
- Complex conditions can be harder to write
Interview Points
- $match = filter stage
- Similar to find()
- Place early in pipeline for performance
- Works with indexes