[[time-series]]
== Time Series

MongoDB 5.0 introduced https://docs.mongodb.com/manual/core/timeseries-collections/[Time Series] collections that are optimized to efficiently store documents over time such as measurements or events.
Those collections need to be created as such before inserting any data.
Collections can be created by either running the `createCollection` command, defining time series collection options or extracting options from a `@TimeSeries` annotation as shown in the examples below.

.Create a Time Series Collection
====
.Create a Time Series via the MongoDB Driver
[code,java]
----
template.execute(db -> {

    com.mongodb.client.model.CreateCollectionOptions options = new CreateCollectionOptions();
    options.timeSeriesOptions(new TimeSeriesOptions("timestamp"));

    db.createCollection("weather", options);
    return "OK";
});
----

.Create a Time Series Collection with `CollectionOptions`
[code,java]
----
template.createCollection("weather", CollectionOptions.timeSeries("timestamp"));
----

.Create a Time Series Collection derived from an Annotation
[code,java]
----
@TimeSeries(collection="weather", timeField = "timestamp")
public class Measurement {

    String id;
    Instant timestamp;
    // ...
}

template.createCollection(Measurement.class);
----
====

The snippets above can easily be transferred to the reactive API offering the very same methods.
Make sure to properly _subscribe_ to the returned publishers.

