Database Manual / Time Series / Create & Configure

Create and Query a Time Series Collection创建和查询时间序列集合

This page shows how to create and query a time series collection, with code examples.本页通过代码示例展示了如何创建和查询时间序列集合。

Important

Feature Compatibility Version Requirement功能兼容性版本要求

You can only create time series collections on a system with featureCompatibilityVersion set to 5.0 or greater.您只能在featureCompatibilityVersion设置为5.0或更高版本的系统上创建时间序列集合。

Create a Time Series Collection创建时间序列集合

1

Define the timeField as the field that contains time data and the metaField as the field that contains metadata:timeField定义为包含时间数据的字段,将metaField定义为含有元数据的字段:

{
timeField: "timestamp",
metaField: "metadata"
}

In this example, timestamp is the name of the timeField and metadata is the name of the metaField. The value of the timestamp field must be a date type.在这个例子中,timestamptimeField的名称,metadatametaField的名称。时间戳字段的值必须是日期类型。

Important

Choosing the right metaField for your collection optimizes both storage and query performance. 为集合选择正确的metaField可以优化存储和查询性能。For more information on metaField selection and best practices, see metaFields.有关metaField选择和最佳实践的更多信息,请参阅metaFields

2

Define the time interval for each bucket of data using one of the two approaches below:使用以下两种方法之一定义每个数据桶的时间间隔:

Important

Changing Time Series Intervals更改时间序列间隔

After creation, you can modify granularity or bucket definitions using the collMod method. However, you can only increase the time span covered by each bucket. You cannot decrease it.创建后,您可以使用collMod方法修改粒度或桶定义。但是,您只能增加每个桶覆盖的时间跨度。你不能减少它。

  1. Define a granularity field:定义granularity字段:

    {
    granularity: "seconds"
    }

    For more detailed information on selecting a granularity value, see Granularity Considerations.有关选择granularity值的更多详细信息,请参阅粒度注意事项

OR

  1. In MongoDB 6.3 and later, you can define bucketMaxSpanSeconds and bucketRoundingSeconds fields. Both values must be the same:在MongoDB 6.3及更高版本中,您可以定义bucketMaxSpanSecondsbucketRoundingSeconds字段。两个值必须相同:

    {
    bucketMaxSpanSeconds: "300",
    bucketRoundingSeconds: "300"
    }
3

Optionally, set expireAfterSeconds to expire documents when the value of the timeField is at least that old:(可选)将expireAfterSeconds设置为当timeField的值至少为旧值时使文档过期:

{
expireAfterSeconds: 86400
}
4

Create the collection using either the db.createCollection() method or the create command. 使用db.createCollection()方法或create命令创建集合。The follow example uses the db.createCollection() method to create a weather time series collection:以下示例使用db.createCollection()方法创建weather时间序列集合:

db.createCollection(
"weather",
{
timeseries: {
timeField: "timestamp",
metaField: "metadata",
granularity: "seconds"
},
expireAfterSeconds: 86400
}
)

Time Series Field Reference时间序列字段参考

A time series collection includes the following fields:时间序列集合包括以下字段:

Field字段Type类型Description描述
timeseries.timeFieldstring字符串Required. The name of the field which contains the date in each time series document. Documents in a time series collection must have a valid BSON date as the value for the timeField.必修的。每个时间序列文档中包含日期的字段的名称。时间序列集合中的文档必须具有有效的BSON日期作为timeField的值。
timeseries.metaFieldstring字符串

Optional. 可选。The name of the field which contains metadata in each time series document. The metadata in the specified field should be data that is used to label a unique series of documents. 每个时间序列文档中包含元数据的字段的名称。指定字段中的元数据应该是用于标记一系列唯一文档的数据。The metadata should rarely, if ever, change The name of the specified field may not be _id or the same as the timeseries.timeField. The field can be of any data type.元数据应该很少(如果有的话)更改。指定字段的名称可能不是_id或与timeseries.timeField不同。该字段可以是任何数据类型。

Although the metaField field is optional, using metadata can improve query optimization. 虽然metaField字段是可选的,但使用元数据可以改善查询优化。For example, MongoDB automatically creates a compound index on the metaField and timeField fields for new collections. 例如,MongoDB会自动在metaFieldtimeField字段上为新集合创建复合索引If you do not provide a value for this field, the data is bucketed solely based on time.如果不为此字段提供值,则数据将仅基于时间进行分组。

timeseries.granularityinteger整数

Optional. 可选。Do not use if setting bucketRoundingSeconds and bucketMaxSpanSeconds.如果设置bucketRoundingSecondsbucketMaxSpanSeconds,则不要使用。

Possible values are seconds (default), minutes, and hours.可能的值是seconds(默认值)、minuteshours

Set granularity to the value that most closely matches the time between consecutive incoming timestamps. This improves performance by optimizing how MongoDB stores data in the collection.granularity设置为与连续传入时间戳之间的时间最接近的值。这通过优化MongoDB在集合中存储数据的方式来提高性能。

For more information on granularity and bucket intervals, see Set Granularity for Time Series Data.有关粒度和桶间隔的更多信息,请参阅设置时间序列数据的粒度

timeseries.bucketMaxSpanSecondsinteger整数

Optional. 可选。Use with bucketRoundingSeconds as an alternative to granularity. Sets the maximum time between timestamps in the same bucket.使用bucketRoundingSeconds作为granularity的替代方案。设置同一桶中时间戳之间的最大时间间隔。

Possible values are 1-31536000.可能的值为1-31536000。

New in version 6.3.在版本6.3中新增。

timeseries.bucketRoundingSecondsinteger整数

Optional. 可选。Use with bucketMaxSpanSeconds as an alternative to granularity. Must be equal to bucketMaxSpanSeconds.使用bucketMaxSpanSeconds作为粒度的替代方案。必须等于bucketMaxSpanSeconds

When a document requires a new bucket, MongoDB rounds down the document's timestamp value by this interval to set the minimum time for the bucket.当文档需要一个新的桶时,MongoDB会按此间隔对文档的时间戳值进行四舍五入,以设置桶的最小时间。

New in version 6.3.在版本6.3中新增。

expireAfterSecondsinteger整数Optional. 可选。Enable the automatic deletion of documents in a time series collection by specifying the number of seconds after which documents expire. 通过指定文档过期的秒数,启用时间序列集合中文档的自动删除。MongoDB deletes expired documents automatically. See Set up Automatic Removal for Time Series Collections (TTL) for more information.MongoDB会自动删除过期的文档。有关详细信息,请参阅设置时间序列集合(TTL)的自动删除

Other allowed options that are not specific to time series collections are:其他不特定于时间序列集合的允许选项包括:

  • storageEngine
  • indexOptionDefaults
  • collation
  • writeConcern
  • comment

Tip

See: 请参阅:

db.createCollection() and create.

Insert Measurements into a Time Series Collection将测量值插入时间序列集合

Each document you insert should contain a single measurement. To insert multiple documents at once, issue the following command:您插入的每个文档都应该包含一个测量值。要一次插入多个文档,请发出以下命令:

db.weather.insertMany( [
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-18T00:00:00.000Z"),
temp: 12
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-18T04:00:00.000Z"),
temp: 11
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-18T08:00:00.000Z"),
temp: 11
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-18T12:00:00.000Z"),
temp: 12
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-18T16:00:00.000Z"),
temp: 16
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-18T20:00:00.000Z"),
temp: 15
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-19T00:00:00.000Z"),
temp: 13
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-19T04:00:00.000Z"),
temp: 12
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-19T08:00:00.000Z"),
temp: 11
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-19T12:00:00.000Z"),
temp: 12
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-19T16:00:00.000Z"),
temp: 17
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: ISODate("2021-05-19T20:00:00.000Z"),
temp: 12
}
] )

To insert a single document, use the db.collection.insertOne() method.要插入单个文档,请使用db.collection.insertOne()方法。

Tip

Optimize Insert Performance优化插入性能

To learn how to optimize inserts for large operations, see Inserts Best Practices.要了解如何优化大型操作的插入,请参阅插入最佳实践

Query a Time Series Collection查询时间序列集合

You query a time series collection the same way you query a standard MongoDB collection.查询时间序列集合的方式与查询标准MongoDB集合的方式相同。

To return one document from a time series collection, run:要从时间序列集合中返回一个文档,请运行:

db.weather.findOne( {
timestamp: ISODate("2021-05-18T00:00:00.000Z")
} )

Example output:示例输出:

{
timestamp: ISODate("2021-05-18T00:00:00.000Z"),
metadata: { sensorId: 5578, type: 'temperature' },
temp: 12,
_id: ObjectId("62f11bbf1e52f124b84479ad")
}

For more information on time series queries, see Query Best Practices.有关时间序列查询的更多信息,请参阅查询最佳实践

Run Aggregations on a Time Series Collection在时间序列集合上运行聚合

For additional query functionality, use an aggregation pipeline such as:要获得其他查询功能,请使用聚合管道,例如:

db.weather.aggregate( [
{
$project: {
date: {
$dateToParts: { date: "$timestamp" }
},
temp: 1
}
},
{
$group: {
_id: {
date: {
year: "$date.year",
month: "$date.month",
day: "$date.day"
}
},
avgTmp: { $avg: "$temp" }
}
}
] )

The example aggregation pipeline groups all documents by the date of the measurement and then returns the average of all temperature measurements that day:示例聚合管道按测量日期对所有文档进行分组,然后返回当天所有温度测量的平均值:

 {
"_id" : {
"date" : {
"year" : 2021,
"month" : 5,
"day" : 18
}
},
"avgTmp" : 12.714285714285714
}
{
"_id" : {
"date" : {
"year" : 2021,
"month" : 5,
"day" : 19
}
},
"avgTmp" : 13
}