Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Handling Time Series Data

Handling time series data in MongoDB

Time series data is a sequence of data points collected or recorded at specific time intervals. MongoDB is well-suited for storing and querying time series data due to its flexible schema and powerful aggregation capabilities.

Storing Time Series Data

When storing time series data in MongoDB, it's essential to include a timestamp field to record the time of each data point. You can also use additional fields to store metadata about each data point.

Example: Inserting Time Series Data

Below is an example of inserting time series data into a collection:

Insert Time Series Data Example

db.sensorData.insertMany([
    { timestamp: ISODate("2023-01-01T00:00:00Z"), temperature: 20, humidity: 30 },
    { timestamp: ISODate("2023-01-01T01:00:00Z"), temperature: 21, humidity: 31 },
    { timestamp: ISODate("2023-01-01T02:00:00Z"), temperature: 19, humidity: 29 }
])

Querying Time Series Data

Querying time series data involves filtering documents based on the timestamp field. You can also use the aggregation framework to perform more complex analyses.

Example: Querying Data by Time Range

Below is an example of querying data within a specific time range:

Time Range Query Example

db.sensorData.find({
    timestamp: {
        $gte: ISODate("2023-01-01T00:00:00Z"),
        $lt: ISODate("2023-01-02T00:00:00Z")
    }
})

Aggregating Time Series Data

The aggregation framework can be used to perform various analyses on time series data, such as calculating averages, sums, and other statistics over specific time intervals.

Example: Aggregating Data by Hour

Below is an example of using the aggregation framework to calculate the average temperature and humidity for each hour:

Aggregation Example

db.sensorData.aggregate([
    {
        $group: {
            _id: { $hour: "$timestamp" },
            avgTemperature: { $avg: "$temperature" },
            avgHumidity: { $avg: "$humidity" }
        }
    }
])