Collection Configuration
On this page
Overview
In this guide, you can learn how to specify configuration options for a collection in your Mongoid application.
Configure Collection Options
You can specify configuration options for a collection by using the
:collection_options
argument with the store_in
macro. The :collection_options
argument accepts any collection option that
your Ruby driver and MongoDB Server versions support.
Note
You must explicitly create a collection to apply any specified collection options. Create your collection by running the collection management Rake task, as shown in Collection Management Rake Task section of this guide.
To learn more about collection options available in the Ruby driver, see the Collections guide in the Ruby driver documentation.
The following sections show examples of how to configure collection options when using Mongoid.
Time Series Collection
Time series collections efficiently store sequences of measurements over a period of time. The following example shows how to configure a time series collection:
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
To learn more about time series collections, see the Time Series Collections guide in the MongoDB Server manual.
Capped Collection
Capped collections have maximum size or document counts that prevent them from growing beyond a specified threshold. The following example shows how to configure a capped collection:
class Blog include Mongoid::Document store_in collection_options: { capped: true, size: 1024 } end
To learn more about capped collections, see the Capped Collections guide in the MongoDB Server manual.
Default Collation
Collations are sets of rules for how to compare strings, typically in a particular natural language. The following example shows how to specify a default collation to use on a collection:
class Title include Mongoid::Document store_in collection_options: { collation: { locale: 'fr' } } end
To learn more about collations, see the Collation guide in the MongoDB Server manual.
Collection Management Rake Task
To apply the collection options you specify in your Mongoid application, you
must explicitly create the corresponding collection. To do so, use the
db:mongoid:create_collections
Rake task by running the following command in
your shell:
rake db:mongoid:create_collections
You can also run the create_collection
command on a single model in the
Rails console, as shown in the following example:
Model.create_collection