集合配置
Overview
在本指南中,您可以学习;了解如何为 Mongoid应用程序中的集合指定配置选项。
配置集合选项
您可以使用 :collection_options
参数和 store_in
宏来指定集合的配置选项。 :collection_options
参数接受Ruby驾驶员和MongoDB Server版本支持的任何集合选项。
注意
您必须显式创建集合才能应用任何指定的集合选项。 通过运行集合管理Rake任务来创建集合,如本指南的 集合管理 Rake 任务部分所示。
要学习;了解有关Ruby驾驶员中可用集合选项的更多信息,请参阅Ruby驾驶员文档中的集合指南。
以下部分举例说明如何在使用 Mongoid 时配置集合选项。
时间序列集合
时间序列集合可有效存储一段时间内的测量序列。 以下示例展示了如何配置时间序列集合:
class Measurement include Mongoid::Document field :temperature, type: Integer field :timestamp, type: Time store_in collection_options: { time_series: { timeField: "timestamp", granularity: "minutes" }, expire_after: 604800 } end
固定大小集合
固定大小集合具有最大大小或文档计数,以防止它们的增长超过指定阈值。 以下示例展示了如何配置固定大小集合:
class Blog include Mongoid::Document store_in collection_options: { capped: true, size: 1024 } end
默认排序规则
排序规则是指如何比较通常采用特定自然语言的字符串的规则集。 以下示例显示如何指定对集合使用的默认规则:
class Title include Mongoid::Document store_in collection_options: { collation: { locale: 'fr' } } end
集合管理 Rake 任务
要应用您在 Mongoid应用程序中指定的集合选项,您必须显式创建相应的集合。 为此,请通过在Shell中运行以下命令来使用 db:mongoid:create_collections
Rake任务:
rake db:mongoid:create_collections
您还可以在 Rails 控制台中对单个模型运行create_collection
命令,如以下示例所示:
Model.create_collection