Skip to content
Studio 3T - The professional GUI, IDE and client for MongoDB
  • Tools
    • Aggregation Editor
    • IntelliShell
    • Visual Query Builder
    • Export Wizard
    • Import Wizard
    • Query Code
    • SQL Query
    • Connect
    • Schema Explorer
    • Compare
    • SQL ⇔ MongoDB Migration
    • Data Masking
    • Task Scheduler
    • Reschema
    • More Tools and Features
  • Solutions
  • Resources
    • Knowledge Base
    • MongoDB Tutorials & Courses
    • Tool/Feature Documentation
    • Blog
    • Community
    • Testimonials
    • Whitepapers
    • Reports
  • Contact us
    • Contact
    • Sales Support
    • Feedback and Support
    • Careers
    • About Us
  • Store
    • Buy Now
    • Preferred Resellers
    • Team Pricing
  • Download
  • My 3T
search

Studio 3T® Knowledge Base

  • Documentation
  • Tutorials
  • Workshops
Take the fastest route to learning MongoDB. Cover the basics in two hours with MongoDB 101, no registration required.
Start the free course

MongoDB Time Series Collections Explained

Posted on: 22/11/2022 by Dj Walker-Morgan
TL;DR
Need to know

Time series data is data gathered over time, like sensor readings or stock price history. MongoDB Time Series collections allow the repetitive records of time series data to be stored and queried efficiently in a MongoDB database.

Studio 3T added support for Time Series collections in version 2022.9.

In this article, we’ll explain what a Time Series is in general and how MongoDB Time Series collections make it more efficient to store and query those collections.

What is a Time Series

Time Series is a term for data where the most important field is the timestamp, because each entry in a time series represents data for that time.

So say you have a thermometer, it records temperature every minute:

10:00,25.1
10:01,25.2
10:02,25.1
10:03,24.7

This isn’t our only thermometer, so we’d better identify it with some data about the data, the meta data:

Living Room,Sensor 1,10:00,25.1
Living Room,Sensor 1,10:01,25.2
Living Room,Sensor 1,10:02,25.1
Living Room,Sensor 1,10:03,24.7

Now, to store this data in MongoDB we’ll turn it into JSON. (And make those times into proper ISODate types):

{
	timestamp: ISODate("2022-10-06T10:00:00.000Z"),
         location: { 
                room: "Living Room",
           	sensor: "Sensor 1"
        },
	temperature: 25.1
}
{
	timestamp: ISODate("2022-10-06T10:01:00.000Z"),
        location: { 
                room: "Living Room",
           	sensor: "Sensor 1"
         },
	temperature: 25.2
}
{
	timestamp: ISODate("2022-10-06T10:02:00.000Z"),
        location: { 
                room: "Living Room",
           	sensor: "Sensor 1"
        },
	temperature: 25.1
}
{
	timestamp: ISODate("2022-10-06T10:03:00.000Z"),
         location: { 
                room: "Living Room",
           	sensor: "Sensor 1"
         },
	temperature: 24.7
} 

This is easy to import into MongoDB, but consider the following things:

  • To average the temperature for those four minutes would involve retrieving and aggregating four different documents.
  • Each one of those four documents repeats the same values for the location and sensor information.

Doesn’t sound too bad does it? Until you think of, for example, measuring the temperature every second, for a hundred rooms, each with ten sensors in them. 

Doing calculations over time involves searching hundreds of documents in MongoDB. Indexing the location and sensor and time gives you some big indexes, so that’s not an option. Also there’s going to be a massive amount of repetition in the database, chewing up all your storage.

Compressing the data

What we’d ideally like to do, in order to save space, is accumulate all the entries for one particular location in a single record.

{
	 location: { 
                room: "Living Room",
           	sensor: "Sensor 1"
          },
          Data: {
                  timestamp: {
                   	0: ISODate("2022-10-06T10:00:00.000Z"),
                   	1: ISODate("2022-10-06T10:01:00.000Z"),
                   	2: ISODate("2022-10-06T10:02:00.000Z"),
                   	3: ISODate("2022-10-06T10:03:00.000Z")
                   },
                   temperature: {
                   	0: 25.1,
                   	1: 25.2,
                   	2: 25.1,
                   	3: 24.7
                   }
           }
}   

Now, to perform calculations, we only have one document to retrieve and the metadata only appears once. Each field’s data point is also indexed so that it should be even quicker to retrieve.

But this is also a huge pain to manage. And MongoDB documents max size is 16MB so we can’t keep everything in one document. We could divide them up into blocks of time with a document per block, but oh no! Then it’s even more complicated!

And that’s where MongoDB Time Series collections comes to the rescue.

What are MongoDB Time Series Collections?

What if we could tell MongoDB that one field is a timestamp and another is metadata and everything else was data points? And what if MongoDB did all the transformational magic for you to make things quicker and more compressed? And what if you could carry on working with a collection, as simple, uncompressed documents and have MongoDB speed up all your operations?

That’s what a MongoDB Time Series collection does. You create a MongoDB Time Series collection in Studio 3T like any other collection, but at creation time you can tell MongoDB the name of the field with the timestamp in it and the name of the field with the meta data. Let’s create a roomtemps collection.

Creating MongoDB Time Series Collections with Studio 3T

Our time field is timestamp and our meta field is location.

The granularity setting is a hint to MongoDB as to what to expect in terms of density of data points. It defaults to seconds, but if your data comes in every minute or hour, you may want to adjust it. The Expire After Seconds is also optional. Setting this can delete your data in a time series collection after a certain amount of time. That’s useful if your collection is only of “hot” or recent data. We’ll leave both of those alone, and click on create.

We can now add our JSON documents from earlier, exactly as they are shown and then query the collection:

Viewing a MongoDB Time Series Collection as a Time Series
Viewing a MongoDB Time Series Collection as a Time Series

This looks pretty much the same as the documents we just inserted. That’s because in the background, MongoDB created a system collection – system.buckets.roomtemps – to store the data in, in a format that looks more like our single-document-with-all-the-data from earlier. 

The collection we are working with – roomtemps – looks like a simple collection of single, point-in-time documents, because that’s how we want to visualize our Time Series data in MongoDB, so it’s easy to work with in aggregation.  

If we look at system.buckets.roomtemps collection we can see our compressed document.

Viewing the underlying data structure of a MongoDB Time Series Collection
Viewing the underlying data structure of a MongoDB Time Series Collection

There’s one difference – there’s a control section which holds minimum and maximum values for all the data fields. Why? Optimization! You don’t need to do anything when querying this data but MongoDB can use the min and max values to quickly find bits of the time series or values which are within ranges. And because many time series queries are “What happened over this range of time”, it really can optimize the queries.

Indexes and Time Series Collections.

With all this optimization, there’s still one thing that can be done to boost query performance on Time Series collections. Adding a secondary index on the metadata’s fields (and adding the timestamp) will give a strong index for retrieving by location:

Indexing MongoDB Time Series Collections
Indexing MongoDB Time Series Collections

Aggregating with MongoDB Time Series Collections

The real power of Time Series comes when you need to aggregate the data. With the support for Time Series collections came a number of new aggregation stages built with this kind of data in mind. That doesn’t mean that these stages only work with Time Series collections, just that they work better with time series data. For example, we have written about the $setWindowFields stage in the Studio 3T Blog using normal collections. But it can enable some powerful time series aggregations.

$setWindowFields

The problem with aggregation is that, without stashing data in variables, it regards each document in isolation. That’s where the $setWindowFields comes in as it combines some of aggregation’s $group functionality with window functions. 

{ 
    "partitionBy" : { location:"$location", day: { $dayOfYear: "$timestamp" } }, 
    "output" : { 
        "averaged" : { 
            "$avg" : "$temperature", 
            "window" : { 
                documents: [ "unbounded", "unbounded" ]
            }
        }
    }
}

The “partitionBy” section splits and groups the data up by our meta data and, in this case by the day of the year. The “output” section then defines what output should be added to every document, based on their partition. So our first field is an “averaged” field for the temperature. This will be the average for that partition. The “window” section says use the entire partition to work out the average, “unbounded”. The result of this stage is that every document gets the average temperature for its partition added to it. 

Add on a $match:

{
     "$expr": { $lt: [ "$temperature", "$averaged" ] }    
}

And now the result of the aggregation is every incident when a location had a lower than average temperature for that day.

You can change that window to work with moving windows, adjusting the boundaries of the average calculation too. Or compare documents relative to each other. And if you want more than an average calculation, there’s a host of window operators including accumulators, ranking, ordering, and gap-filling.

Of course, you can use any aggregation you want with a Time Series collection. We’re just mentioning $setWindowFields as it’s almost custom-made for Time Series data analysis.

End of Time Series

This is just a quick introduction to Time Series collections. You should now understand why you would use them (to reduce storage needs and optimize for time) and that there are MongoDB aggregations that will let you leverage your ability to efficiently store Time Series data. From version 2022.9, Studio 3T will let you create Time Series collections. A final note though, there are limitations on MongoDB Time Series collections which you should note as they are implicit to how they are implemented.


How helpful was this article?
This article was hideous
This article was bad
This article was ok
This article was good
This article was great
Thank you for your feedback!

About The Author

Dj Walker-Morgan

Dj has been around since Commodore had Pets and Apples grew everywhere. With a background in Unix and development, he's been around the technology business writing code or writing content ever since.

Article navigation

Related articles

  • Time Series Collections in Studio 3T
  • What’s so good about Time Series Collections?
  • What’s new in Studio 3T 2022.9 – Time Series and default Mongosh
  • How do you make Studio 3T export MongoDB collections to unique files? #Studio3T_AMA
  • How to get MongoDB statistics for all collections? #Studio3T_AMA

Studio 3T

MongoDB Enterprise Certified Technology PartnerSince 2014, 3T has been helping thousands of MongoDB developers and administrators with their everyday jobs by providing the finest MongoDB tools on the market. We guarantee the best compatibility with current and legacy releases of MongoDB, continue to deliver new features with every new software release, and provide high quality support.

Find us on FacebookFind us on TwitterFind us on YouTubeFind us on LinkedIn

Education

  • Free MongoDB Tutorials
  • Connect to MongoDB
  • Connect to MongoDB Atlas
  • Import Data to MongoDB
  • Export MongoDB Data
  • Build Aggregation Queries
  • Query MongoDB with SQL
  • Migrate from SQL to MongoDB

Resources

  • Feedback and Support
  • Sales Support
  • Knowledge Base
  • FAQ
  • Reports
  • White Papers
  • Testimonials
  • Discounts

Company

  • About Us
  • Blog
  • Careers
  • Legal
  • Press
  • Privacy Policy
  • EULA

© 2023 3T Software Labs Ltd. All rights reserved.

  • Privacy Policy
  • Cookie settings
  • Impressum

We value your privacy

With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data.

By clicking “Accept all”, you consent to the storage of cookies and the processing of personal data for these purposes, including any transfers to third countries. By clicking on “Decline all”, you do not give your consent and we will only store cookies that are necessary for our website. You can customize the cookies we store on your device or change your selection at any time - thus also revoking your consent with effect for the future - under “Manage Cookies”, or “Cookie Settings” at the bottom of the page. You can find further information in our Privacy Policy.
Accept all
Decline all
Manage cookies
✕

Privacy Preference Center

With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data. Please choose for which purposes you wish to give us your consent and store your preferences by clicking on “Accept selected”. You can find further information in our Privacy Policy.

Accept all cookies

Manage consent preferences

Essential cookies are strictly necessary to provide an online service such as our website or a service on our website which you have requested. The website or service will not work without them.

Performance cookies allow us to collect information such as number of visits and sources of traffic. This information is used in aggregate form to help us understand how our websites are being used, allowing us to improve both our website’s performance and your experience.

Google Analytics

Google Ads

Bing Ads

Facebook

LinkedIn

Quora

Hotjar

Reddit

Functional cookies collect information about your preferences and choices and make using the website a lot easier and more relevant. Without these cookies, some of the site functionality may not work as intended.

HubSpot

Social media cookies are cookies used to share user behaviour information with a third-party social media platform. They may consequently effect how social media sites present you with information in the future.

Accept selected