Query and Aggregation
Query Fundamentals
graph LR
A[MongoDB Queries] --> B[Simple Queries]
A --> C[Complex Queries]
A --> D[Aggregation Pipeline]
Advanced Query Techniques
Comparison Operators
## Find users older than 25
db.users.find({ age: { $gt: 25 } })
## Find users between 20 and 30
db.users.find({
age: {
$gte: 20,
$lte: 30
}
})
Logical Operators
## AND condition
db.users.find({
$and: [
{ age: { $gt: 25 } },
{ city: "Beijing" }
]
})
## OR condition
db.users.find({
$or: [
{ age: { $lt: 20 } },
{ status: "active" }
]
})
Aggregation Framework
Aggregation Pipeline Stages
Stage |
Description |
Example |
$match |
Filter documents |
{ $match: { age: { $gt: 25 } } } |
$group |
Group by field |
{ group: { _id: "department", total: { $sum: 1 } } } |
$sort |
Sort results |
{ $sort: { age: -1 } } |
$limit |
Limit results |
{ $limit: 5 } |
$project |
Select fields |
{ $project: { name: 1, age: 1 } } |
Complex Aggregation Example
db.sales.aggregate([
## Match sales over $1000
{ $match: { amount: { $gt: 1000 } } },
## Group by product and calculate total sales
{ $group: {
_id: "$product",
totalSales: { $sum: "$amount" },
averagePrice: { $avg: "$amount" }
}},
## Sort by total sales descending
{ $sort: { totalSales: -1 } },
## Limit to top 5 products
{ $limit: 5 }
])
Text Search Capabilities
## Create text index
db.articles.createIndex({ content: "text" })
## Perform text search
db.articles.find({
$text: { $search: "mongodb tutorial" }
})
Geospatial Queries
## Create geospatial index
db.locations.createIndex({ location: "2dsphere" })
## Find nearby locations
db.locations.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.9667, 40.78]
},
$maxDistance: 1000
}
}
})
Aggregation Pipeline Visualization
graph LR
A[Input Documents] --> B[$match]
B --> C[$group]
C --> D[$sort]
D --> E[$limit]
E --> F[Output Results]
- Use indexes strategically
- Minimize data processing stages
- Use $match early in pipeline
- Limit result sets
- Avoid complex nested aggregations
Advanced Query Patterns
Lookup (Join-like Operation)
db.orders.aggregate([
{ $lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "user_details"
}}
])
Best Practices in LabEx MongoDB Environments
- Profile and analyze query performance
- Use explain() to understand query execution
- Choose appropriate indexing strategies
- Leverage aggregation for complex data transformations
By mastering these query and aggregation techniques, you'll unlock powerful data manipulation capabilities in MongoDB, making your data analysis more efficient and insightful.