Docs 菜单
Docs 主页
/
MongoDB Manual
/

分片时间序列集合

在此页面上

  • 先决条件
  • 步骤
  • 更多信息

5.1 版本中的新功能

使用本教程对新的或现有的时间序列集合进行分片。

重要

在完成本教程之前,请查看时间序列集合的分片限制

要对时间序列集合进行分片,必须部署分片集群来托管包含您的时间序列集合的数据库。

1

mongosh连接到分片集群的mongos 。 指定运行mongoshostport

mongosh --host <hostname> --port <port>
2

运行 sh.status() 以确认您的数据库已启用分片:

sh.status()

该命令返回分片信息:

--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
...
3

使用带有时间序列选项的 shardCollection() 方法。

例如:

sh.shardCollection(
"test.weather",
{ "metadata.sensorId": 1 },
{
timeseries: {
timeField: "timestamp",
metaField: "metadata",
granularity: "hours"
}
}
)

在此示例中,sh.shardCollection()

  • test 数据库上分割名为 weather 的新时间序列集合。

  • metadata.sensorId 字段指定为分片键

  • granularity 指定为小时。

以下文档包含集合的相应元数据:

db.weather.insertOne( {
"metadata": { "sensorId": 5578, "type": "temperature" },
"timestamp": ISODate("2021-05-18T00:00:00.000Z"),
"temp": 12
} )
1

mongosh 连接到分片集群的 mongos。指定运行 mongoshostport

mongosh --host <hostname> --port <port>
2

运行 sh.status() 以确认您的数据库已启用分片:

sh.status()

该命令返回分片信息:

--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
...
3

创建支持分片的索引,以便在集合上启用分片。

考虑具有以下属性的时间序列集合:

db.createCollection(
"deliverySensor",
{
timeseries: {
timeField: "timestamp",
metaField: "metadata",
granularity: "minutes"
}
}
)

集合中的示例文档如下所示:

db.deliverySensor.insertOne( {
"metadata": { "location": "USA", "vehicle": "truck" },
"timestamp": ISODate("2021-08-21T00:00:10.000Z"),
"speed": 50
} )

运行以下命令,以便在 metadata.location 字段创建哈希索引:

db.deliverySensor.createIndex( { "metadata.location" : "hashed" } )
4

使用 shardCollection() 方法对集合进行分片。

若要对上一步中所述的 deliverySensor 集合进行分片,请运行以下命令:

sh.shardCollection( "test.deliverySensor", { "metadata.location": "hashed" } )

在此示例中,sh.shardCollection()

  • test 数据库上分片名为 deliverySensor 的现有时间序列集合。

  • metadata.location 字段指定为分片键location 是该集合的 metaField 的子字段。

如果指定到 sh.shardCollection() 的集合是时间序列集合,那么您无需指定时间序列选项。

后退

基于时间序列数据构建物化视图

来年

时间序列集合最佳实践