时间序列数据
概述
在本指南中,您可以学习如何使用 C 驱动器存储和交互 时间序列数据。
时间序列数据由以下组件组成
测量量
测量的时间戳
描述测量的元数据
以下表格描述了您可以存储时间序列数据的示例情况
情况 | 测量量 | 元数据 |
---|---|---|
按行业记录月度销售额 | 美元收入 | 公司,国家 |
跟踪天气变化 | 降水水平 | 位置,传感器类型 |
记录房价波动 | 月租金价格 | 位置,货币 |
创建时间序列集合
重要
时间序列集合的服务器版本
要创建和交互时间序列集合,您必须连接到运行 MongoDB 服务器 5.0 或更高版本的部署。
您可以通过创建时间序列集合来存储时间序列数据。要创建时间序列集合,将以下参数传递给mongoc_database_create_collection()
函数
要创建集合的数据库
要创建的新集合的名称
一个
timeseries
对象,该对象指定了timeField
选项
以下示例在 fall_weather
数据库中创建一个名为 october2024
的时间序列集合,并将 timeField
选项设置为 "timestamp"
字段
// Initialize the MongoDB C Driver mongoc_init (); // Create a new client instance mongoc_client_t *client = mongoc_client_new ("<connection string>"); // Get a handle on the database mongoc_database_t *database = mongoc_client_get_database (client, "fall_weather"); // Create options for the time series collection bson_t *opts = BCON_NEW ( "timeseries", "{", "timeField", BCON_UTF8 ("timestamp"), "}"); // Create the time series collection bson_error_t error; mongoc_collection_t *collection = mongoc_database_create_collection (database, "october2024", opts, &error); if (!collection) { fprintf(stderr, "Error creating collection: %s\n", error.message); } bson_destroy (opts);
要验证您是否成功创建了时间序列集合,请在 fall_weather
数据库上运行 mongoc_database_find_collections_with_opts()
函数,并打印结果
// List collections in the database mongoc_cursor_t *cursor = mongoc_database_find_collections_with_opts (database, NULL); const bson_t *doc; while (mongoc_cursor_next (cursor, &doc)) { char *str = bson_as_canonical_extended_json (doc, NULL); printf ("%s\n", str); bson_free (str); } // Check for cursor errors if (mongoc_cursor_error (cursor, &error)) { fprintf (stderr, "Cursor error: %s\n", error.message); } mongoc_cursor_destroy (cursor);
{ "name" : "october2024", "type" : "timeseries", "options" : { "timeseries" : { "timeField" : "timestamp", "granularity" : "seconds", "bucketMaxSpanSeconds" : { "$numberInt" : "3600" } } }, "info" : { "readOnly" : false } } ...
存储时间序列数据
您可以使用 mongoc_collection_insert_one()
或 mongoc_collection_insert_many()
函数将数据插入到时间序列集合中,并在每个插入的文档中指定测量值、时间戳和元数据。
要了解有关将文档插入集合的更多信息,请参阅插入文档指南。
示例
以下示例将纽约市温度数据插入到在创建时间序列集合示例中创建的 october2024
时间序列集合中。每个文档包含以下字段
temperature
,存储温度测量值,单位为华氏度location
,存储位置元数据timestamp
,存储测量值收集的时间
const bson_t *insert_doc = BCON_NEW ( "temperature", BCON_DOUBLE (70.0), "location", "{", "city", BCON_UTF8 ("New York"), "}", "timestamp", BCON_DATE_TIME (1633046400000)); if (!mongoc_collection_insert_one (collection, insert_doc, NULL, NULL, &error)) { fprintf(stderr, "Error inserting document: %s\n", error.message); }
查询时间序列数据
您可以使用与在执行其他集合上的读取或聚合操作时相同的语法和约定来查询存储在时间序列集合中的数据。有关这些操作的更多信息,请参阅其他信息部分。
附加信息
要了解更多关于本指南中提到的概念,请参阅以下 MongoDB 服务器手册条目
要了解更多关于执行读取操作的信息,请参阅从 MongoDB 读取数据。
要了解更多关于执行聚合操作的信息,请参阅使用聚合转换您的数据指南。
API 文档
要了解更多关于本指南中提到的函数,请参阅以下 API 文档