Practical Filtering Techniques
Comprehensive Array Filtering Strategies
Exact Array Matching
## Find documents with exact array match
db.products.find({
tags: ["electronics", "smartphone"]
})
Partial Array Matching
graph LR
A[Array Filtering] --> B[Partial Match]
B --> C[Contains Element]
B --> D[Subset Matching]
Contains Element
## Find products containing specific tag
db.products.find({
tags: "electronics"
})
Advanced Filtering Techniques
Conditional Array Filtering
Technique |
Operator |
Example |
Greater Than |
$gt |
Scores > 80 |
Less Than |
$lt |
Prices < 100 |
Range Match |
$elemMatch |
Complex conditions |
Complex Query Example
## Multi-condition array filtering
db.students.find({
grades: {
$elemMatch: {
$gte: 80,
$lte: 90
}
}
})
Indexing Strategies
Array Index Types
graph TD
A[MongoDB Array Indexes] --> B[Single Field]
A --> C[Compound Index]
A --> D[Multikey Index]
Creating Efficient Indexes
## Create index on array field
db.collection.createIndex({ tags: 1 })
Query Optimization Techniques
- Use selective filtering
- Limit result sets
- Leverage indexes
- Avoid unnecessary complexity
- Minimize large array operations
- Use projection to reduce data transfer
- Monitor query performance
Projection Example
## Selective field retrieval
db.users.find(
{ interests: "technology" },
{ name: 1, interests: 1 }
)
Error Handling Patterns
## Robust query execution
try {
const results = db.collection.find({
arrayField: { $elemMatch: conditions }
}).limit(100)
} catch (error) {
console.error("Query execution failed")
}
Real-world Filtering Scenarios
E-commerce Product Filtering
## Complex product search
db.products.find({
$and: [
{ categories: "electronics" },
{ price: { $lt: 500 } },
{ "features.type": "wireless" }
]
})
By mastering these practical filtering techniques, developers can efficiently query and manipulate array data in MongoDB with precision and performance.