时间序列集合
Overview
在本指南中,您可以学习;了解如何使用 Laravel 集成来创建时间序列集合并与之交互。这些集合存储时间序列数据,由以下部分组成:
测量数量
测量的时间戳
描述测量的元数据
下表描述了可以存储时间序列数据的示例情况:
情况 | 测量数量 | Metadata |
---|---|---|
按行业记录月度销售额 | 收入(美元) | 公司、国家/地区 |
追踪天气变化 | 降水量 | 位置、传感器类型 |
记录房价波动 | 月租价格 | 位置、货币 |
创建时间序列集合
重要
时间序列集合的服务器版本
要创建时间序列集合并与之交互,必须连接到运行 MongoDB Server 5.0或更高版本的部署。
您可以创建时间序列集合来存储时间序列数据。要创建时间序列集合,请创建一个迁移类并添加 up()
函数以指定集合配置。在 up()
函数中,将新集合的名称和 timeseries
选项传递给 Schema::create()
方法。
提示
要学习;了解有关创建迁移类的更多信息,请参阅模式构建器指南中的 执行 Laravel 迁移。
设置 timeseries
选项时,请包含以下字段:
timeField
:指定在每个时间序列文档中存储时间戳的字段。metaField
:指定每个时间序列文档中存储元数据的字段。granularity
:指定连续时间戳之间的大致时间。 可能的值为'seconds'
、'minutes'
和'hours'
。
例子
此示例迁移类使用以下配置创建 precipitation
时间序列集合:
timeField
设置为'timestamp'
metaField
设置为'location'
granularity
设置为'minutes'
declare(strict_types=1); use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\Schema; return new class extends Migration { protected $connection = 'mongodb'; /** * Run the migrations. */ public function up(): void { $options = [ 'timeseries' => [ 'timeField' => 'timestamp', 'metaField' => 'location', 'granularity' => 'minutes', ], ]; Schema::create('precipitation', null, $options); } /** * Reverse the migrations. */ public function down(): void { Schema::drop('precipitation'); } };
要验证是否已成功创建时间序列集合,请调用 Schema::hasCollection()
方法并将集合名称作为参数传递:
$result = Schema::hasCollection('precipitation'); echo $result;
如果集合存在,则 hasCollection()
方法返回值 true
。
插入时间序列数据
您可以将文档传递给 insert()
方法,并在每个插入的文档中指定测量值、时间戳和元数据,从而将数据插入到时间序列集合中。
例子
此示例将纽约市降水数据插入到创建时间序列集合示例中创建的precipitation
时间序列集合中。 每个文档包含以下字段:
precipitation_mm
,以毫米为单位存储降水量测量值location
,用于存储位置元数据timestamp
,其中存储了测量集合的时间
$data = [ [ 'precipitation_mm' => 0.5, 'location' => 'New York City', 'timestamp' => new UTCDateTime(Carbon::create(2023, 9, 12, 0, 0, 0, 'CET')), ], [ 'precipitation_mm' => 2.8, 'location' => 'New York City', 'timestamp' => new UTCDateTime(Carbon::create(2023, 9, 17, 0, 0, 0, 'CET')), ], ]; $result = DB::table('precipitation') ->insert($data);
注意
前面的示例使用 Laravel查询构建器将文档插入到时间序列集合中。或者,您可以创建一个表示集合的Eloquent 模型,并在模型上执行插入操作。要学习;了解更多信息,请参阅 Eloquent 模型类指南。
查询时间序列集合
您可以使用与对其他集合执行读取或聚合操作时相同的语法和约定来查询时间序列集合中存储的数据。 要查找有关这些操作的更多信息,请参阅“其他信息”部分。
更多信息
要学习;了解有关本指南中提到的概念的更多信息,请参阅以下MongoDB Server手册条目: