Overview
在本指南中,您可以了解 MongoDB 中的时间序列集合,以及如何在 MongoDB Go 驱动程序中与其进行交互。
时间序列集合可有效存储一段时间内的测量序列。 该collection由具有以下信息的time-series数据组成:
随着时间推移收集的数据
描述测量的元数据
测量日期
例子 | 测量 | Metadata |
|---|---|---|
销售数据 | 收入 | 公司 |
感染率 | 感染人数 | 地点 |
创建时间序列集合
重要
时间序列集合需要 MongoDB 5.0或更高版本。
要创建time-series collection,请将以下参数传递给CreateCollection()方法:
要创建的新集合的名称
至少指定时间字段的
TimeSeriesOptions对象
例子
以下示例在db数据库中创建march2022时间序列集合,并将temperature作为时间字段:
db := client.Database("db")
// Creates a time series collection that stores "temperature" values over timetso := options.TimeSeries().SetTimeField("temperature")opts := options.CreateCollection().SetTimeSeriesOptions(tso)
db.CreateCollection(context.TODO(), "march2022", opts)要检查是否已创建集合,请将"listCollections"命令发送到RunCommand()方法:
// Creates a command to list collectionscommand := bson.D{{"listCollections", 1}}var result bson.M
// Runs the command on the databasecommandErr := db.RunCommand(context.TODO(), command).Decode(&result)if commandErr != nil { panic(commandErr)}
// Prints the command resultsoutput, outputErr := json.MarshalIndent(result, "", " ")if outputErr != nil { panic(outputErr)}fmt.Printf("%s\n", output)查询时间序列集合
要查询时间序列集合,请使用与检索和聚合数据相同的约定。
更多信息
要了解有关提到的操作的更多信息,请参阅以下指南:
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: