Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序Ruby MongoDB 驱动程序

集合

在此页面上

  • 时间序列集合
  • 固定大小集合
  • 将现有collection转换为固定大小集合
  • 文档验证
  • 向现有collection添加验证
  • 列出collection
  • 删除collection

MongoDB 将文档存储在collection中。如果集合不存在,MongoDB 会在您首次在该集合中插入文档时创建该集合。

您还可以使用各种选项显式创建集合,例如设置最大大小或文档验证规则。

MongoDB 5.0 中添加了时间序列集合。 您可以在此处阅读文档。

时间序列集合可有效存储一段时间内的测量序列。 Time series data is any data that is collected over time and is uniquely identified by one or more unchanging parameters. 标识time-series数据的不变参数通常是数据源的元数据。

要创建时间序列集合,您必须使用时间序列选项显式创建集合:

opts = {
time_series: {
timeField: "timestamp",
metaField: "metadata",
granularity: "hours"
},
expire_after: 604800
}
db['weather', opts].create

创建时间序列集合时,请指定以下选项:

字段
说明
time_series[:timeField]
必需。包含每个时间序列文档中日期的字段的名称。
time_series[:metaField]
可选。包含每个时间序列文档中元数据的字段的名称。指定字段中的元数据应用于标识一系列唯一文档的数据。元数据应该很少改变(如果有的话)。
time_series[:granularity]
可选。 可能的值为“秒”、“分钟”和“小时”。 默认情况下,MongoDB 将粒度设置为“秒”,以进行高频摄取。
:expireAfterSeconds
可选。 通过指定文档过期后的秒数,启用自动删除时间序列集合中文档的功能。 MongoDB 会自动删除过期文档。

有关time-series collection选项的更多信息,请参阅MongoDB Docs

插入时间序列集合与插入常规集合类似:

db['weather'].insert_many([
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 18, 0, 0, 0),
temp: 12
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 18, 4, 0, 0),
temp: 11
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 18, 8, 0, 0),
temp: 11
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 18, 12, 0, 0),
temp: 12
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 18, 16, 0, 0),
temp: 16
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 18, 20, 0, 0),
temp: 15
}, {
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 19, 0, 0, 0),
temp: 13
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 19, 4, 0, 0),
temp: 12
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 19, 8, 0, 0),
temp: 11
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 19, 12, 0, 0),
temp: 12
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 19, 16, 0, 0),
temp: 17
},
{
metadata: { sensorId: 5578, type: "temperature" },
timestamp: Time.utc(2021, 5, 19, 20, 0, 0),
temp: 12
}
])

查询时间序列集合也与查询常规集合非常相似:

weather.find(timestamp: Time.utc(2021, 5, 18, 0, 0, 0)).first

此查询的结果:

{
"timestamp" => 2021-05-18 00:00:00 UTC,
"metadata" => {
"sensorId" => 5578,
"type" => "temperature"
},
"temp" => 12,
"_id" => BSON::ObjectId('624dfb87d1327a60aeb048d2')
}

聚合管道还可用于其他查询功能:

weather.aggregate([
{
"$project": {
date: {
"$dateToParts": { date: "$timestamp" }
},
temp: 1
}
},
{
"$group": {
_id: {
date: {
year: "$date.year",
month: "$date.month",
day: "$date.day"
}
},
avgTmp: { "$avg": "$temp" }
}
}
]).to_a

聚合管道示例按测量日期对所有文档进行分组,然后返回当日所有温度测量值的平均值:

[{
"_id" => {
"date" => {
"year" => 2021,
"month" => 5,
"day" => 18
}
},
"avgTmp" => 12.833333333333334
},
{
"_id" => {
"date" => {
"year" => 2021,
"month" => 5,
"day" => 19
}
},
"avgTmp" => 12.833333333333334
}]

有关更多信息,请参阅有关time-series collection的 MongoDB 文档。

固定大小集合具有最大大小或文档数,可以防止其增长超过最大阈值。所有固定大小集合都必须指定最大大小,也可以指定最大文档数。如果集合在达到最大文档计数之前达到最大大小限制,MongoDB 会删除较旧的文档。

要创建固定大小集合,请使用capped: true选项和size (以字节为单位)。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
collection = client[:artists, capped: true, size: 10000]
collection.create
collection.capped? # => true

要将现有collection从非固定大小转换为固定大小,请使用convertToCapped命令。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
db = client.database
db.command({ 'convertToCapped' => 'artists', 'size' => 10000 })

如果您使用的是 MongoDB 3.2 或更高版本,则可以使用文档验证。 collection具有验证会将每个插入或更新的文档与验证器选项中指定的条件进行比较。根据validationLevelvalidationAction的不同,如果文档不符合指定条件,MongoDB 要么返回警告,要么拒绝插入或更新文档。

contacts以下示例创建了一个带有验证器的collection,该验证器指定插入或更新的文档应至少匹配以下三个条件之一:

  • phone字段是一个字符串

  • email字段与正则表达式匹配

  • status字段为UnknownIncomplete

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
client[:contacts,
{
'validator' => { '$or' =>
[
{ 'phone' => { '$type' => "string" } },
{ 'email' => { '$regex' => /@mongodb\.com$/ } },
{ 'status' => { '$in' => [ "Unknown", "Incomplete" ] } }
]
}
}
].create

要将文档验证条件添加到现有collection,请使用collMod命令。contactsage以下示例演示了如何向collection添加验证,确保所有新文档必须包含为数字的字段。

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
db = client.database
db.command({ 'collMod' => 'contacts',
'validator' =>
{ 'age' =>
{ '$type' => "number" }
}
})

对数据库对象使用collectionscollection_names方法列出集合:

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
database = client.database
database.collections # Returns an array of Collection objects.
database.collection_names # Returns an array of collection names as strings.

要删除collection,请对该对象调用drop

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
artists.drop
←  数据库索引 →