对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

设置时间序列数据的粒度

创建时间序列集合时,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> } }, ... }, ... ] } }

以下示例将 weather24h 集合的 granularity 设置为 minutes:

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 秒(而不是将 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 或更新版本,才能修改分片时间序列集合的精度。