Complex Sorting Techniques
Array Field Sorting
Sorting based on array fields requires special techniques in MongoDB:
## Sort by the first element of an array
db.products.find().sort({'tags.0': 1})
## Sort by array length
db.users.find().sort({hobbies: {$size: 1}})
Nested Document Sorting
Sorting nested documents involves dot notation:
## Sort by nested field
db.users.find().sort({'address.city': 1})
Sorting Workflow
graph TD
A[Complex Sorting] --> B{Sorting Type}
B -->|Array Fields| C[Sort by Array Elements]
B -->|Nested Documents| D[Sort by Nested Fields]
B -->|Computed Values| E[Sort by Calculated Fields]
Computed Field Sorting
Create dynamic sorting using aggregation:
db.orders.aggregate([
{$addFields: {
totalAmount: {$sum: '$items.price'}
}},
{$sort: {totalAmount: -1}}
])
Advanced Sorting Techniques
Technique |
Description |
Example |
Text Score Sorting |
Sort by search relevance |
db.articles.find({$text: {$search: "mongodb"}}).sort({score: {$meta: "textScore"}}) |
Conditional Sorting |
Sort with complex conditions |
db.users.find().sort({age: 1, status: {$cond: [{$eq: ['$active', true]}, 1, 0]}}) |
Geospatial Sorting
Sort documents based on proximity:
db.locations.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.9667, 40.78]
}
}
}
})
- Use indexes for complex sorting
- Avoid sorting large datasets
- Utilize
.explain()
to analyze query performance
Handling Null and Missing Values
## Custom null handling in sorting
db.users.find().sort({
email: 1,
username: {$ifNull: ['$username', 'Unknown']}
})
Explore advanced sorting techniques with LabEx to master MongoDB querying!