当您创建时间序列集合时,MongoDB 会自动创建 system.buckets 系统集合并将传入的时间序列数据分组到存储桶中。通过设置粒度,您可以根据数据摄取率来控制数据的分组频率。
从 MongoDB 6.3 开始,可以使用自定义分桶参数 bucketMaxSpanSeconds 和 bucketRoundingSeconds 来指定存储桶边界,并更准确地控制时间序列数据的分桶方式。
注意
必须运行 MongoDB 5.0.1 或更高版本,才能在创建时间序列集合后更改集合的粒度。
检索当前分桶参数
要检索当前集合值,请使用 listCollections 命令:
db.runCommand( { listCollections: 1 } )
对于时间序列集合,输出会包含 granularity、bucketMaxSpanSeconds 和 bucketRoundingSeconds 参数(如果存在)。
{ cursor: { id: <number>, ns: 'test.$cmd.listCollections', firstBatch: [ { name: <string>, type: 'timeseries', options: { expireAfterSeconds: <number>, timeseries: { timeField: <string>, metaField: <string>, granularity: <string>, bucketMaxSpanSeconds: <number>, bucketRoundingSeconds: <number> } }, ... }, ... ] } }
使用“granularity”参数
下表显示了使用给定 granularity 值时一个数据桶中包含的最长时间间隔:
granularity | granularity 存储桶限额 |
|---|---|
| 1 小时 |
| 24 小时 |
| 30天 |
默认情况下,granularity设置为 seconds。可以将 granularity 值设置为最接近同一数据源传入测量值之间的时间跨度,从而提高性能。 例如,若要记录来自数千个传感器的天气数据,但每五分钟仅记录一次来自每个传感器的数据,请将 granularity 设置为 "minutes"。
db.createCollection( "weather24h", { timeseries: { timeField: "timestamp", metaField: "metadata", granularity: "minutes" }, expireAfterSeconds: 86400 } )
将 granularity 设置为 hours 会将长达一个月的数据导入事件分组到单个存储桶中,从而拖延遍历时间并减慢查询速度。将其设置为 seconds 会导致每个轮询间隔有多个存储桶,其中许多可能只包含一个文档。
提示
使用自定义存储桶参数
在 MongoDB 6.3 及更高版本中,您可以手动使用两个自定义分桶参数来设置存储桶边界,而不是 granularity。如果您希望按固定时间间隔(例如从午夜开始每 4 小时一次)查询数据,请考虑使用此方法。确保存储桶在这些时间段之间不重叠,可优化高查询量和 insert 操作。
要使用自定义分桶参数,请将两个参数设置为相同的值,并且不要设置 granularity:
bucketMaxSpanSeconds设置同一存储桶中不同时间戳之间的最大时间间隔。可能的值为 1-31536000。bucketRoundingSeconds设置确定新存储桶的起始时间戳的时间间隔。当文档需要新的存储桶时,MongoDB 会按此间隔对文档的时间戳值向下取整,以设置存储桶的最短时间间隔。
对于气象站示例,如果每 4 小时生成一次概要报告,您可以通过将自定义分桶参数设置为 14400 秒(而不是将 granularity 设置为 "minutes")来调整分桶:
db.createCollection( "weather24h", { timeseries: { timeField: "timestamp", metaField: "metadata", bucketMaxSpanSeconds: 14400, bucketRoundingSeconds: 14400 } } )
如果时间为 2023-03-27T16:24:35Z 的文档不适合现有存储桶,MongoDB 将创建一个新存储桶,其最小时间为 2023-03-27T16:00:00Z,最大时间为 2023-03-27T19:59:59Z。
更改时间序列粒度
您可以使用 collMod 命令,将 timeseries.granularity 从较短的时间单位增加到较长的时间单位。
db.runCommand( { collMod: "weather24h", timeseries: { granularity: "seconds" | "minutes" | "hours" } } )
要更新自定义分桶参数 bucketRoundingSeconds 和 bucketMaxSpanSeconds 而不是 granularity,请将这两个自定义参数包含在 collMod 命令中并将它们设置为相同的值:
db.runCommand( { collMod: "weather24h", timeseries: { bucketRoundingSeconds: 86400, bucketMaxSpanSeconds: 86400 } } )
您无法减少粒度间隔或自定义分桶值。
注意
必须运行 MongoDB 6.0 或更新版本,才能修改分片时间序列集合的精度。