Docs HomeMongoDB Manual

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

Create the collection using either the db.createCollection() method or the create command. For example:使用db.createCollection()方法或create命令创建集合。例如

db.createCollection(
"weather",
{
timeseries: {
timeField: "timestamp",
metaField: "metadata"
}})
2

Set the timeField to the field that contains time data, and the metaField to the field that contains metadata:timeField设置为包含时间数据的字段,将metaField设置为含有元数据的字段:

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

Define the time interval for each bucket of data using one of the two approaches below. 使用以下两种方法之一定义每个数据桶的时间间隔。For more detailed information, see Set Granularity for Time Series Data.有关更多详细信息,请参阅设置时间序列数据的粒度

Important

Changing Time Series Granularity改变时间序列粒度

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

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

    timeseries: {
    timeField: "timestamp",
    metaField: "metadata",
    granularity: "seconds"
    }

OR

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

    timeseries: {
    timeField: "timestamp",
    metaField: "metadata",
    bucketMaxSpanSeconds: "300",
    bucketRoundingSeconds: "300"
    }
4

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

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.timeFieldstringRequired. 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.metaFieldstringOptional. 可选的。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 type.指定字段的名称不能为_id,也不能与timeseries.timeField相同。字段可以是任何类型。
timeseries.granularityintegerOptional. 可选的。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. granularity设置为与连续传入时间戳之间的时间最匹配的值。This improves performance by optimizing how MongoDB stores data in the collection.这通过优化MongoDB在集合中存储数据的方式来提高性能。
For more information on granularity and bucket intervals, see Set Granularity for Time Series Data.有关粒度和存储段间隔的更多信息,请参阅设置时间序列数据的粒度
timeseries.bucketMaxSpanSecondsintegerOptional. 可选的。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.bucketRoundingSecondsintegerOptional.可选的。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版新增。
timeseries.expireAfterSecondsintegerOptional.可选的。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. 通过指定文档过期的秒数,启用自动删除时间序列集合中的文档。MongoDB会自动删除过期文档。See Set up Automatic Removal for Time Series Collections (TTL) for more information.有关详细信息,请参阅为时间序列集合(TTL)设置自动删除

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

  • storageEngine
  • indexOptionDefaults
  • collation
  • writeConcern
  • comment

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 Optimize Inserts.要了解如何优化大型操作的插入,请参阅优化插入

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 Optimize Query Performance.有关时间序列查询的详细信息,请参阅优化查询性能

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
}