设置时间序列数据的粒度
当您创建时间序列集合时,MongoDB 自动创建一个system.buckets
系统集合 并将传入的时间序列数据分组到桶中。通过设置粒度,您可以控制数据基于数据摄入率进行分桶的频率。
从MongoDB 6.3版本开始,您可以使用自定义分桶参数 bucketMaxSpanSeconds
和 bucketRoundingSeconds
来指定分桶边界,更精确地控制时间序列数据如何分桶。
有关分桶的更多信息,请参阅 关于时间序列数据。
注意
为了在创建集合后更改时间序列集合的粒度,您必须运行MongoDB 5.0.1或更高版本。请参阅 MongoDB 5.0已知问题。
检索当前分桶参数
要检索当前集合值,请使用 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> } }, ... }, ... ] } }
设置“粒度”参数
以下示例将 weather24h
集合的 粒度
设置为 hours
db.createCollection( "weather24h", { timeseries: { timeField: "timestamp", metaField: "metadata", granularity: "minutes" }, expireAfterSeconds: 86400 } )
使用自定义分桶参数
在MongoDB 6.3及以上版本中,您可以使用两个自定义分桶参数手动设置桶边界,而不是使用granularity
。如果您预计要查询固定时间间隔的数据,例如从午夜开始每隔4小时查询一次,请考虑这种方法。确保在这些期间内桶不重叠,可以优化查询量和insert
操作。
要使用自定义分桶参数,请将这两个参数设置为相同的值,并且不要设置granularity
bucketMaxSpanSeconds
设置同一桶中时间戳之间的最大时间。可能的值为1-31536000。bucketRoundingSeconds
设置确定新桶起始时间戳的时间间隔。当一个文档需要新的桶时,MongoDB会通过此间隔向下舍入文档的时间戳值,以设置桶的最小时间。
对于气象站示例,如果您每4小时生成一次汇总报告,您可以调整分桶,将自定义分桶参数设置为14400秒,而不是使用"minutes"
的granularity
。
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或更高版本。