An application running in production generates a continuous stream of operational data. It records API response times, CPU usage, memory consumption, request counts, database latency, error rates, and other measurements that help developers understand application behavior.
For example, an API monitoring service might record the response time of every request along with the service name, endpoint, HTTP status code, and timestamp. As the application grows, these records can quickly become one of the largest datasets in the database.
Storing this information in ordinary MongoDB collections is possible, but developers must consider how to organize, index, query, and retain large volumes of time-based records. Creating too many indexes can increase storage requirements, while an unsuitable document structure can make data ingestion and historical analysis less efficient.
MongoDB Time Series Collections are designed for this type of workload. They organize measurements internally into buckets based on time and metadata, allowing MongoDB to optimize storage and queries for time-based data.
This article explains how to use time series collections to store application metrics, design the metadata structure, insert measurements efficiently, query historical information, and manage data retention.
What Are MongoDB Time Series Collections?
A time series collection stores measurements associated with a particular point in time.
A measurement normally contains three types of information:
Timestamp: When the measurement was recorded.
Metadata: Which application, service, device, or resource produced the measurement.
Measurement values: The actual information being recorded, such as response time, CPU usage, or memory consumption.
For example, an application monitoring service might generate this document:
{
timestamp: ISODate("2026-11-24T10:15:00Z"),
metadata: {
service: "OrderAPI",
environment: "Production",
instance: "api-server-01"
},
responseTimeMs: 125,
requestCount: 340,
errorCount: 4,
cpuUsage: 62.5,
memoryUsageMB: 1024
}
This document represents the measurements collected from one application instance at a particular time.
If the monitoring service collects metrics every minute, it continuously inserts similar documents with different timestamps and measurement values.
MongoDB time series collections are optimized for this pattern. Instead of treating every measurement as an entirely independent storage unit, MongoDB groups measurements with matching metadata and nearby timestamps into internal buckets.
This reduces storage overhead and allows MongoDB to perform time-based operations more efficiently.
Understanding the Time Series Collection Structure
A time series collection is configured with two important fields:
The timeField is required and must contain a BSON Date value.
The metaField is optional, but it is strongly recommended for application monitoring because it helps MongoDB group related measurements.
For example, consider the following documents:
{
timestamp: ISODate("2026-11-24T10:00:00Z"),
metadata: {
service: "OrderAPI",
instance: "server-01"
},
responseTimeMs: 120
}
{
timestamp: ISODate("2026-11-24T10:01:00Z"),
metadata: {
service: "OrderAPI",
instance: "server-01"
},
responseTimeMs: 135
}
{
timestamp: ISODate("2026-11-24T10:00:00Z"),
metadata: {
service: "PaymentAPI",
instance: "server-02"
},
responseTimeMs: 90
}
The first two measurements belong to the same metadata group and have nearby timestamps. MongoDB can organize them within the same bucket.
The third measurement belongs to a different service and instance, so it is stored in a different metadata group.
This organization is important because the choice of metadata affects both storage efficiency and query performance.
Creating a Time Series Collection for Application Metrics
Let's build a monitoring collection for an application that records API performance information.
First, create a database:
use ApplicationMonitoring
Next, create a time series collection:
db.createCollection(
"apiMetrics",
{
timeseries: {
timeField: "timestamp",
metaField: "metadata",
granularity: "minutes"
}
}
);
The configuration contains three important settings.
The timeField identifies the timestamp field. MongoDB uses this value to organize measurements according to their time range.
The metaField identifies the metadata object. In this example, it contains information about the application service, deployment environment, and server instance.
The granularity setting tells MongoDB approximately how frequently measurements arrive from the same source. The available predefined values are seconds, minutes, and hours.
For example, if an application records metrics every minute, minutes is a reasonable starting point.
Choosing the correct granularity matters because it influences how MongoDB groups measurements into buckets. A setting that is too fine can create many small buckets, while a setting that is too coarse can create buckets covering unnecessarily large time ranges.
MongoDB also supports custom bucket intervals through bucketMaxSpanSeconds and bucketRoundingSeconds. These options allow developers to define more precise bucket time ranges when the predefined granularity settings do not match the workload.
Designing Metadata for Application Monitoring
Metadata design is one of the most important decisions when creating a time series collection.
A good metadata field contains information that identifies the source of a measurement and remains relatively stable over time.
For application metrics, useful metadata fields might include:
Application or service name.
Environment, such as Development, Testing, or Production.
Server or container instance identifier.
Region or deployment location.
Device or sensor identifier.
For example:
metadata: {
service: "OrderAPI",
environment: "Production",
instance: "server-01",
region: "ap-south"
}
This structure makes it possible to retrieve measurements for a particular service, environment, or server instance.
Avoid putting frequently changing values into metadata.
For example, response time, CPU usage, memory consumption, HTTP status code, and request count should normally be measurement fields rather than metadata.
If every document contains a different metadata value, MongoDB may create many short-lived, sparsely populated buckets. This reduces the benefit of bucket-based storage.
Also avoid placing unique request IDs or transaction IDs in metadata when they are not needed to identify a long-lived time series. These values can create unnecessary metadata cardinality.
A useful design rule is to keep metadata focused on the identity of the measurement source and place changing operational values in the measurement fields.
Inserting Application Metrics
Once the collection is created, application services can insert measurements using ordinary MongoDB insert operations.
The following example inserts several API metric records:
db.apiMetrics.insertMany(
[
{
timestamp: ISODate("2026-11-24T10:00:00Z"),
metadata: {
service: "OrderAPI",
environment: "Production",
instance: "server-01"
},
responseTimeMs: 120,
requestCount: 340,
errorCount: 3,
cpuUsage: 58.2,
memoryUsageMB: 980
},
{
timestamp: ISODate("2026-11-24T10:01:00Z"),
metadata: {
service: "OrderAPI",
environment: "Production",
instance: "server-01"
},
responseTimeMs: 145,
requestCount: 360,
errorCount: 5,
cpuUsage: 61.4,
memoryUsageMB: 995
},
{
timestamp: ISODate("2026-11-24T10:02:00Z"),
metadata: {
service: "OrderAPI",
environment: "Production",
instance: "server-01"
},
responseTimeMs: 110,
requestCount: 325,
errorCount: 2,
cpuUsage: 55.8,
memoryUsageMB: 1002
}
],
{
ordered: false
}
);
The insertMany operation sends multiple documents in one database request rather than requiring a separate network round trip for each measurement.
For high-volume monitoring systems, batch insertion can reduce network overhead and improve ingestion efficiency.
MongoDB's time series best practices also recommend grouping documents with identical metadata values in the same batch when possible. This helps the database organize incoming measurements efficiently.
Using ordered: false allows MongoDB to continue processing other documents if an individual insert fails. Applications should still inspect the result and handle write errors appropriately.
For larger monitoring workloads, batch size should be selected based on document size, ingestion rate, network conditions, and the application's latency requirements.
Querying Metrics for a Specific Application Service
Once measurements have been inserted, developers can query them using familiar MongoDB operations.
For example, suppose you want to retrieve all OrderAPI measurements collected during a particular time range.
db.apiMetrics.find(
{
"metadata.service": "OrderAPI",
"metadata.environment": "Production",
timestamp: {
$gte: ISODate("2026-11-24T10:00:00Z"),
$lt: ISODate("2026-11-24T11:00:00Z")
}
}
).sort({
timestamp: 1
});
This query applies two types of filtering.
The metadata conditions identify the service and environment. The timestamp conditions restrict the result to measurements collected within the specified hour.
Filtering by metadata and time is a common pattern for monitoring applications. It helps MongoDB identify relevant buckets and avoid examining unnecessary historical data.
For example, a dashboard showing the performance of the OrderAPI should not need to retrieve measurements from every service running in the environment.
Use the actual time range required by the dashboard or monitoring operation instead of requesting the entire history.
Calculating Average API Response Time
Application monitoring usually requires more than retrieving individual measurements. Developers often need aggregated information such as average response time, total requests, error counts, and CPU utilization.
MongoDB aggregation pipelines are useful for these calculations.
The following example calculates average response time for the OrderAPI during a selected time range:
db.apiMetrics.aggregate([
{
$match: {
"metadata.service": "OrderAPI",
"metadata.environment": "Production",
timestamp: {
$gte: ISODate("2026-11-24T10:00:00Z"),
$lt: ISODate("2026-11-24T11:00:00Z")
}
}
},
{
$group: {
_id: null,
averageResponseTime: {
$avg: "$responseTimeMs"
},
totalRequests: {
$sum: "$requestCount"
},
totalErrors: {
$sum: "$errorCount"
},
averageCpuUsage: {
$avg: "$cpuUsage"
}
}
}
]);
The $match stage filters the relevant service and time range before aggregation.
The $group stage calculates the required metrics across the matching measurements.
The result provides a summary that can be displayed on an application monitoring dashboard.
For more useful reports, group measurements by service, server instance, or time interval instead of using _id: null.
For example, grouping by metadata.instance allows developers to compare the performance of different application servers and identify whether a particular instance is behaving differently from the others.
Grouping Metrics by Time Intervals
Monitoring dashboards frequently display measurements as time-based charts.
For example, an operations team may want to see average API response time every five minutes instead of viewing every individual metric record.
MongoDB provides the $dateTrunc aggregation operator for grouping timestamps into fixed time intervals.
db.apiMetrics.aggregate([
{
$match: {
"metadata.service": "OrderAPI",
timestamp: {
$gte: ISODate("2026-11-24T09:00:00Z"),
$lt: ISODate("2026-11-24T12:00:00Z")
}
}
},
{
$group: {
_id: {
interval: {
$dateTrunc: {
date: "$timestamp",
unit: "minute",
binSize: 5
}
}
},
averageResponseTime: {
$avg: "$responseTimeMs"
},
totalRequests: {
$sum: "$requestCount"
},
totalErrors: {
$sum: "$errorCount"
}
}
},
{
$sort: {
"_id.interval": 1
}
}
]);
The $dateTrunc operator groups measurements into five-minute intervals.
For example, measurements collected at 09:01, 09:02, 09:03, and 09:04 are grouped into the same five-minute interval.
This approach reduces the number of records that a dashboard needs to process while preserving useful information about changes in application performance.
Be careful when interpreting averages. An average of pre-aggregated averages can produce misleading results if the groups contain different numbers of requests. When each document represents a different number of requests, use the appropriate weighting or store sufficient information to calculate the correct overall average.
Indexing Time Series Collections
Indexes help MongoDB locate relevant data without scanning unnecessary records.
For time series collections, indexes should support the queries that the application actually performs.
Starting with MongoDB 6.3, newly created time series collections automatically receive a compound index on the metaField and timeField.
For the apiMetrics collection, MongoDB creates an index based on metadata and timestamp.
You can inspect indexes using:
db.apiMetrics.getIndexes();
Additional secondary indexes can be created for commonly queried measurement fields:
db.apiMetrics.createIndex({
"metadata.service": 1,
timestamp: 1,
responseTimeMs: 1
});
The index design should reflect actual query patterns.
For example, a dashboard that filters by service and time range may benefit from an index that supports those fields. A separate index on responseTimeMs may be useful if the application frequently searches for measurements above a particular response-time threshold.
Time series indexes work differently from ordinary collection indexes internally. MongoDB indexes bucket-level information rather than creating an independent index entry for every measurement in the same way as a regular collection.
Time series collections also have index restrictions. For example, unique indexes and text indexes are not supported.
Avoid creating indexes for every metric field. Each additional index consumes storage and adds maintenance work during writes. Use query plans and actual workload observations to determine which indexes provide meaningful benefits.
Managing Historical Data With Automatic Expiration
Application metrics can grow continuously. Keeping every measurement forever may increase storage requirements and make historical data management more complicated.
MongoDB supports automatic expiration for time series collections through the expireAfterSeconds collection option.
For example, if an application needs to retain metrics for 30 days, create a collection with the following configuration:
db.createCollection(
"apiMetrics",
{
timeseries: {
timeField: "timestamp",
metaField: "metadata",
granularity: "minutes"
},
expireAfterSeconds: 2592000
}
);
The value 2592000 represents 30 days in seconds.
MongoDB automatically removes expired time series data through its background expiration process.
Expiration is based on the timeField value, not the time when the document was inserted. This matters when measurements arrive late or are imported from another system.
Also, expiration is not an exact deletion deadline. The background cleanup process removes expired data asynchronously, so records may remain available for some time after their expiration threshold.
For applications with different retention requirements for different services, consider whether separate collections or supported partial TTL index strategies are more appropriate. Do not assume that one collection-level expiration setting can provide independent retention periods for every metadata value.
Important Design Considerations for Production Applications
Time series collections are optimized for measurement-oriented workloads, but they are not a replacement for every MongoDB collection.
First, design the document structure around stable metadata and frequently changing measurements. Poor metadata selection can create excessive bucket cardinality and reduce storage efficiency.
Second, keep measurement schemas consistent. MongoDB's column-oriented compression works more effectively when documents have predictable fields and field ordering. Avoid inserting empty objects and arrays unnecessarily. If a measurement does not have a value, omitting the field may be better than inserting an empty structure.
Third, design the collection around the application's ingestion frequency. A service recording one measurement every few minutes has different bucket requirements from a service generating hundreds of measurements per second.
Fourth, understand the update limitations. Time series collections are optimized for inserts and historical queries rather than frequent modifications. Update operations have restrictions: update match expressions can only specify the metaField, and updates can modify only the metaField. Design the application so that measurements are generally inserted as new records rather than repeatedly modified.
Fifth, consider late-arriving measurements. Monitoring agents may temporarily lose connectivity and send older measurements when they reconnect. Test how delayed timestamps affect ingestion, bucket organization, and historical queries.
Finally, monitor storage growth, ingestion errors, query performance, and expiration behavior. A collection that works well with a small test dataset may behave differently when it receives measurements from thousands of application instances.
Conclusion
MongoDB Time Series Collections provide a specialized storage model for applications that continuously generate timestamped measurements. They organize data into internal buckets using metadata and time ranges, helping improve storage efficiency and support historical queries.
For application monitoring, developers can use time series collections to record API response times, request counts, error rates, CPU usage, memory consumption, and other operational metrics.
The most important design decisions are choosing a stable metaField, selecting an appropriate time granularity, batching measurements efficiently, and creating indexes that match real query patterns.
When combined with aggregation pipelines and automatic data expiration, time series collections provide a practical foundation for building application monitoring systems without implementing a separate storage model for every type of metric.
Join the conversation! Your thoughts help the community grow.