Practical Examples
Real-World Scenarios of MongoDB Projection
1. User Profile Data Retrieval
## Retrieve selective user information
mongo userDatabase
db.users.find(
{ status: "active" },
{
name: 1,
email: 1,
lastLogin: 1,
_id: 0
}
)
2. Salary Management System
db.employees.aggregate([
{
$project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
annualSalary: {
$cond: {
if: { $gte: ["$salary", 50000] },
then: { $multiply: ["$salary", 1.1] },
else: "$salary"
}
},
taxBracket: {
$switch: {
branches: [
{ case: { $gte: ["$salary", 100000] }, then: "High" },
{ case: { $gte: ["$salary", 50000] }, then: "Medium" }
],
default: "Low"
}
}
}
}
])
Projection Techniques Comparison
Scenario |
Basic Projection |
Conditional Projection |
Simple Selection |
{ name: 1, age: 1 } |
$cond with complex logic |
Dynamic Transformation |
Limited |
Highly flexible |
Performance Impact |
Minimal |
Moderate |
Advanced Data Masking Example
db.sensitiveData.aggregate([
{
$project: {
username: 1,
email: {
$concat: [
{ $substr: ["$email", 0, 3] },
"****",
{ $substr: ["$email", -4, 4] }
]
},
phoneNumber: {
$cond: {
if: { $ne: ["$role", "admin"] },
then: {
$concat: [
{ $substr: ["$phoneNumber", 0, 3] },
"****",
{ $substr: ["$phoneNumber", -2, 2] }
]
},
else: "$phoneNumber"
}
}
}
}
])
Visualization of Projection Flow
graph LR
A[Original Document] --> B{Projection Rules}
B --> C[Transformed Document]
B --> D[Filtered Fields]
B --> E[Conditional Modifications]
- Use projection to reduce data transfer
- Minimize complex conditional logic
- Leverage LabEx environment for testing
- Profile and optimize aggregation pipelines
Common Projection Patterns
- Data anonymization
- Selective field retrieval
- Dynamic field generation
- Conditional data transformation
Error Handling Considerations
{
$project: {
safeField: {
$ifNull: ["$potentiallyNullField", "Default Value"]
}
}
}
Best Practices for Conditional Projection
- Keep projection logic simple
- Avoid nested complex conditions
- Use appropriate MongoDB operators
- Test thoroughly in staging environments