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

时间序列集合

在本指南中,您可以了解 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()方法:

package main import ( "context" "encoding/json" "fmt" "log" "os" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options") func main() { var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/zh-cn/docs/drivers/go/current/usage-examples/") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer client.Disconnect(context.TODO()) db := client.Database("myDB") // 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)}

要查询时间序列集合,请使用与检索和聚合数据相同的约定。

要了解有关提到的操作的更多信息,请参阅以下指南:

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: