Practical Query Examples
Real-World Min/Max Query Scenarios
Database Setup
mongo
use labex_examples
1. E-commerce Product Queries
Finding Price Ranges
db.products.aggregate([
{
$group: {
_id: "$category",
cheapestProduct: { $min: "$price" },
mostExpensiveProduct: { $max: "$price" }
}
}
]);
2. Employee Salary Analysis
Department Salary Insights
db.employees.aggregate([
{
$group: {
_id: "$department",
lowestSalary: { $min: "$salary" },
highestSalary: { $max: "$salary" },
salaryRange: {
$subtract: [{ $max: "$salary" }, { $min: "$salary" }]
}
}
}
]);
3. Time-Based Queries
Tracking User Activity
db.userLogs.aggregate([
{
$group: {
_id: "$userId",
firstLogin: { $min: "$timestamp" },
lastLogin: { $max: "$timestamp" }
}
}
]);
Query Strategy Flowchart
graph TD
A[Input Collection] --> B{Select Grouping Field}
B --> C[Apply Min/Max Operators]
C --> D[Process Results]
D --> E[Analyze Data]
Technique |
Impact |
Recommendation |
Indexing |
High |
Create indexes on query fields |
Limit Results |
Medium |
Use $limit stage |
Projection |
Low |
Select only necessary fields |
Advanced Filtering
Conditional Min/Max
db.sales.aggregate([
{ $match: { region: "North" } },
{
$group: {
_id: "$product",
maxSale: { $max: "$amount" }
}
}
]);
Best Practices
- Use appropriate indexes
- Minimize data processing
- Break complex queries into stages
Powered by LabEx, mastering MongoDB query techniques.