Real-World Scenarios
E-Commerce Product Pricing
Calculating Total Product Value
db.products.aggregate([
{
$project: {
name: 1,
base_price: "$price",
quantity: 1,
total_value: { $multiply: ["$price", "$quantity"] },
potential_revenue: {
$multiply: [
"$price",
"$quantity",
{ $add: [1, "$profit_margin"] }
]
}
}
}
])
graph TD
A[Product Data] --> B[Base Price]
A --> C[Quantity]
B --> D[Total Value Calculation]
C --> D
D --> E[Potential Revenue]
Financial Portfolio Analysis
db.investments.aggregate([
{
$project: {
stock_name: 1,
initial_investment: 1,
current_price: 1,
shares: 1,
total_current_value: { $multiply: ["$current_price", "$shares"] },
profit_loss: {
$multiply: [
{ $subtract: ["$current_price", "$initial_price"] },
"$shares"
]
}
}
}
])
Logistics and Shipping Calculations
Weight-Based Shipping Costs
db.shipping_orders.aggregate([
{
$project: {
order_id: 1,
base_weight: 1,
packaging_factor: 1.1,
total_weight: { $multiply: ["$base_weight", "$packaging_factor"] },
shipping_rate: 1.5,
total_shipping_cost: {
$multiply: [
{ $multiply: ["$base_weight", "$packaging_factor"] },
"$shipping_rate"
]
}
}
}
])
Scenario Comparison
Scenario |
Key Multiplication |
Complexity |
Use Case |
E-Commerce |
Price * Quantity |
Low |
Revenue Calculation |
Finance |
Current Price * Shares |
Medium |
Portfolio Valuation |
Logistics |
Weight * Shipping Rate |
High |
Shipping Cost |
Advanced Scenario: Manufacturing Cost Analysis
db.manufacturing.aggregate([
{
$project: {
product_id: 1,
raw_material_cost: 1,
labor_hours: 1,
hourly_rate: 1,
overhead_rate: 0.2,
total_labor_cost: { $multiply: ["$labor_hours", "$hourly_rate"] },
total_production_cost: {
$multiply: [
{ $add: [
"$raw_material_cost",
{ $multiply: ["$labor_hours", "$hourly_rate"] }
]},
{ $add: [1, "$overhead_rate"] }
]
}
}
}
])
- Use indexes on frequently multiplied fields
- Limit aggregation pipeline stages
- Leverage LabEx's performance monitoring tools
- Precompute complex calculations when possible
Error Handling Strategies
Robust Multiplication Approach
db.complex_data.aggregate([
{
$project: {
safe_calculation: {
$multiply: [
{ $ifNull: ["$value1", 0] },
{ $ifNull: ["$value2", 1] },
{ $cond: {
if: { $and: [
{ $ne: ["$value1", null] },
{ $ne: ["$value2", null] }
]},
then: 1,
else: 0
}}
]
}
}
}
])
By exploring these real-world scenarios, you'll develop a comprehensive understanding of multiplication techniques in MongoDB aggregations.