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