Now that we can filter our queries, let's extract meaningful insights from the data. Insight is a powerful feature that aggregates data across documents using MongoDB aggregation pipelines. Think of it like a kitchen display system that shows the chef exactly how many of each ingredient they need to prepare - total yogurt amount, number of each topping, etc.
First, define the Insight class in your constant file. Each field uses the accumulate option to specify how values should be aggregated:
Let's break down the aggregation patterns used:
🍦{ $sum: "$size" }
Sums up the size field from all matching orders. If 3 orders have sizes 50, 100, and 200, yogurtIcecreamQty will be 350.
🍓{ $cond: [{ $in: ["strawberry", "$toppings"] }, 1, 0] }
A conditional expression: if "strawberry" is in the toppings array, count 1; otherwise 0. The $sum aggregates these to get the total count.
Add dictionary entries for the insight fields to enable proper labeling in the UI:
Now let's create a View component to display the aggregated insights in a beautiful dashboard layout:
The View component displays each insight metric in a responsive grid. The chef can quickly see how much yogurt to prepare and which toppings are most popular.
Now create a Zone component that connects the View to the store. Zone components handle data fetching and state management:
Key feature of the Zone component:
🔗st.slice[sliceName].use.icecreamOrderInsight(): Auto-generated hook that retrieves the aggregated insight data for the specified slice. The framework handles all the aggregation pipeline execution.
Finally, add the Insight Zone to your page to display real-time aggregated statistics:
Now when users filter orders by status, the insight dashboard automatically updates to show aggregated statistics for only those filtered orders. This is incredibly powerful for real-time operational decisions!
🎉 What You've Accomplished:
- ✓ Created dynamic Query Makers with searchable parameters
- ✓ Learned how to define Insight classes with MongoDB aggregation pipelines
- ✓ Built View components to display aggregated statistics
- ✓ Connected Zone components to auto-generated store hooks
- ✓ Integrated insights with filtered queries for real-time analytics
In the next tutorial, we'll explore how to relate data between different models. This will allow you to create rich relationships like associating orders with customers, linking products to categories, and building complex data graphs.