Optimize MongoDB for time-series data storage and retrieval.
Instruction: Describe how you would structure a MongoDB database and which features you would utilize to optimize it for storing and querying time-series data efficiently.
Updated
Official answer
Define the event timestamp, stable series identity, expected arrival rate, lateness, query windows and retention. Use a BSON Date timeField and an appropriate stable metaField, such as device identity, when a MongoDB time-series collection fits the workload.
MongoDB groups measurements into internal buckets using time and metadata. Choose supported granularity/bucket settings from the interval between measurements; this storage grouping does not itself calculate hourly averages. Validate the exact server version's update, index and transaction limitations before treating a time-series collection like an ordinary collection.
Inspect existing indexes before adding another. Since 6.3, newly created time-series collections with metadata receive a compound metadata/time index. Test the actual device-and-time predicates with explain. For summaries, keep count and sum when an overall mean must combine unequal-sized groups: means of 10 from 2 samples and 20 from 8 samples combine to 18, not 15.
Do not assume partitioning by increasing time spreads writes evenly. Shard keys containing timeField are deprecated from MongoDB 8.0; evaluate supported metadata keys and skew. Define retention and late-data correction, and test burst ingestion, out-of-order events and range-query latency.