Group result by 15 minutes time interval in MongoDb
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
In MongoDB, grouping results by time intervals is a common requirement for data analysis tasks, especially in scenarios such as time series data analysis, IoT data processing, and logging. MongoDB provides powerful aggregation capabilities that allow for flexible and efficient data manipulation. In this article, we'll delve into how to group results by a 15-minute time interval using MongoDB's aggregation framework.
Understanding the Aggregation Framework
MongoDB's aggregation framework facilitates data aggregation operations, allowing you to process data records and return computed results. The framework's pipeline-based approach of breaking tasks into stages enables complex data manipulations. The basic concept involves the use of stages such as $match, $group, $sort, and others to efficiently process and transform data.
Grouping by Time Intervals
When dealing with time-based data, grouping data into consistent time intervals, such as 15-minute segments, enables meaningful summarization and analysis. Suppose you have a collection of timestamped documents in your MongoDB database, you can utilize the $dateToParts and $dateFromParts operators to achieve the desired grouping.
Example: Grouping by 15-Minute Intervals
Consider a collection named sensorData with documents structured as follows:
To group these entries into 15-minute intervals, perform the following steps using the MongoDB aggregation framework:
- Extract Date Components: Use the
$dateToPartsoperator to extract components of the date such as the hour, minute, etc. - Calculate 15-Minute Interval: Manipulate the minute component to represent the start of a 15-minute interval. This is done by dividing and then multiplying by 15 to align the timestamp to the nearest 15-minute mark.
- Recreate Date: Utilize
$dateFromPartsto construct a new date with modified components. The aim is to create a bucket border for the 15-minute interval. - Group by Interval: Employ the
$groupstage to aggregate data based on this newly constructed interval date.
Here is what the aggregation pipeline might look like:
Explanation of the Aggregation Pipeline
- $addFields Stage:
parts: Extracts the date components.intervalStart: Computes a new date object rounded down to the nearest 15-minute mark using$dateFromParts.
- $group Stage:
- Aggregates records by the computed interval start date.
- Calculates metrics such as
averageValueandcount.
- $sort Stage:
- Sorts the results by the interval to ensure chronological order.
Key Points Summary
| Aspect | Explanation |
| Date Extraction | Use $dateToParts to get components. |
| Interval Calculation | Manipulate minute with $floor and $multiply to determine the interval start. |
| Date Reconstruction | Recreate date using $dateFromParts. |
| Grouping and Aggregation | Utilize $group to aggregate based on interval. |
| Sorting | Employ $sort to order results. |
Additional Considerations
Performance
- Indexes: Ensure that the
timestampfield is indexed to improve the performance of the aggregation. - Sharding: Consider sharding your collection if dealing with large datasets to distribute the load across multiple nodes.
Extensions
- Dynamic Intervals: The interval can be parameterized to support different ranges like 30-minute or hourly intervals.
- Multiple Metrics: Extend the aggregation to compute additional metrics like max, min, or sum values.
By leveraging MongoDB's aggregation framework with techniques to manipulate and group date components, you can efficiently extract insights from time-based data, aligning perfectly with various analytical needs.
Related reading
- H2-Console is not showing in browser
- H2-In memory database console not opening
- H2 Console throwing a error webAllowOthers in H2 database
- H2 database console spring boot Load denied by X-Frame-Options
- H2 Database not found error 90146. H2 database is not created on start
- H2 in-memory database. Table not found
- Hadoop on cassandra database
- Handling asynchronous database queries in node.js and mongodb

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.