Docs Menu
Docs Home
/ / /
Mongoid
/

Persistence Configuration

On this page

  • Overview
  • Default Collection Name
  • Persistence Context Attributes
  • Customize Your Persistence Configuration
  • Model-Level Persistence Options
  • Runtime Persistence Options
  • Global Persistence Contexts
  • Client and Collection Access
  • mongo_client.with
  • collection.with
  • API Documentation

In this guide, you can learn about how Mongoid persists data in your database and collections. Persistence configuration refers to the settings that control how Mongoid stores data in MongoDB. This includes the client, database, and collection where documents for a model class are stored, as well as other configuration options such as read and write preferences. This guide provides methods and examples that you can use to access and update the persistence configuration of a model class.

Note

The term "client" refers to a host configuration defined under clients in your mongoid.yml file. Most applications use a single client named default.

By default, Mongoid stores documents in a collection whose name is the pluralized form of its representative class name. In the following example, for the Restaurant class, the corresponding collection is named restaurants. For the Person class, the corresponding collection is named people.

class Restaurant
include Mongoid::Document
end
class Person
include Mongoid::Document
end

However, the default rules of pluralization don't always work. For example, suppose your model is named Rey. The plural form of this word in Spanish is reyes, but the default collection name is reys.

You can create a new pluralization rule for your model class by calling the ActiveSupport::Inflector::Inflections.plural instance method and passing the singular and plural forms of your class name. The following example specifies reyes as the plural of rey:

ActiveSupport::Inflector.inflections do |inflect|
inflect.plural("rey", "reyes")
end

As a result, Mongoid stores Rey model class documents in the reyes collection.

Note

BSON Document Structure

When Mongoid stores a document in a database, it serializes the Ruby object to a BSON document that has the following structure:

{
"_id" : ObjectId("4d3ed089fb60ab534684b7e9"),
"title" : "Sir",
"name" : {
"_id" : ObjectId("4d3ed089fb60ab534684b7ff"),
"first_name" : "Durran"
},
"addresses" : [
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e0"),
"city" : "Berlin",
"country" : "Deutschland"
}
]
}

Every model class contains the following methods, which you can use to retrieve information about where Mongoid persists the model:

  • client_name: Retrieves the client name

  • database_name: Retrieves the database name

  • collection_name: Retrieves the collection name

The following example shows how to retrieve and print the names of the client, database, and collection where documents for the Band class are persisted:

puts Band.client_name
puts Band.database_name
puts Band.collection_name
default
my_bands
bands

Mongoid provides both model-level and runtime options for customizing your persistence configuration. The following sections describe these options.

Suppose you want to store your model's documents in a collection with a different name than the pluralized form of the model class name. You can use the store_in macro to change the collection, database, or client where Mongoid stores a model's documents. The following example shows how to use the store_in macro to store documents from the Person class in a collection called citizens in the other database within a client named analytics:

class Person
include Mongoid::Document
store_in collection: "citizens", database: "other", client: "analytics"
end

The store_in macro can also accept a lambda function. This is useful if you want to define a persistence context with values that cannot use a constant string.

You might want to use this pattern in a multi-tenant application, where multiple users share common access to an application. By using a lambda, you can define a persistence context based on information that is local to the current thread so that users cannot access each others' data.

The following example stores documents in a database determined by a thread-local variable:

class Band
include Mongoid::Document
store_in database: ->{ Thread.current[:database] }
end

You can use the with method on a model class or instance to change a model's persistence configuration for a group of operations during runtime.

Call the with method on a model class or instance and pass options that define a persistence context. You can call the with method in two ways:

  • with(context, options): context is an instance of Mongoid::PersistenceContext and options is a Hash that represents a customizable set of options.

  • with(options): options is a Hash that represents a customizable set of options.

Then, use a block to define the operations that you want to execute in the specified context. The context that you define only exists while the code in the block runs.

By default, Mongoid stores documents for the Band class in a collection called bands. The following code example uses the with method to temporarily use a different client, database, and collection to perform operations on the Band class's documents:

class Band
include Mongoid::Document
field :name, type: String
field :likes, type: Integer
end
# Creates document in 'bands' collection in 'music-non-stop' database within
# default cluster
Band.with(database: "music-non-stop") do |band_class|
band_class.create(name: "Medusa and the Polyps")
end
# Deletes all documents in 'artists' collection within default database
Band.with(collection: "artists") do |band_class|
band_class.delete_all
end
band = Band.new(name: "Japanese Breakfast")
# Perform operations on tertiary cluster
band.with(client: :tertiary) do |band_object|
band_object.save!
band.save!
end

Note

Define Clients

In the preceding example, you must define the tertiary cluster under clients in your mongoid.yml file.

Important

Block Scope

You must call the with method with a block. This is because Mongoid uses the options you pass to the method to create a new client in the background. A block defines the scope of this client so it can be closed and its resources freed.

You can also pass the with method configuration options for read or write operations. The configurations apply only to the specified type of operation.

The following example uses the with method to specify the use of the secondary node for all read operations within the block.

Band.with(read: {mode: :secondary}) do
Band.count
# This write operation runs in the
# new persistence context, but is
# not affected by the read preference.
Band.create(name: "Metallica")
end

Note

Ensuring Consistency in Contexts

When you perform an operation in one context, Mongoid doesn't automatically perform the same operation in different contexts. For example, if you insert a Band model document into the artists collection, the same document will not be inserted into the bands collection.

In previous examples in this section, you changed persistence context only in the scope of a block. You can use Mongoid to globally define a custom persistence context that all operations in your program use. This lets you change the persistence context for all operations at runtime without repeatedly calling the with method.

You can use the following methods to globally define the persistence context in your program:

  • Mongoid.override_client: Mongoid performs all operations on the specified client.

  • Mongoid.override_database: Mongoid performs all operations on the specified database.

In the following code example, the application stores information for different locales in different databases. The code shows how to use the Mongoid.override_database method to globally set the persistence context based on the locale:

class BandsController < ApplicationController
before_action :switch_database
after_action :reset_database
private
def switch_database
I18n.locale = params[:locale] || I18n.default_locale
Mongoid.override_database("my_db_name_#{I18n.locale}")
end
def reset_database
Mongoid.override_database(nil)
end
end

In the preceding example, Mongoid performs all other operations on this thread on an alternative database determined by the locale. Because the after_action macro sets the override option to nil, subsequent requests with no changes in persistence configuration use the default configuration.

You can access the client or collection of a model or document instance by using the mongo_client and collection class methods:

Band.mongo_client
band.mongo_client
Band.collection
band.collection

When using these methods, you can also set runtime persistence options by calling the with method, similar to examples in the Runtime Persistence Options section.

The following code example accesses the client used by the Band model class. It then uses the with method on the client to write to the music database, setting the w write option to 0 to not require write acknowledgement.

Band.mongo_client.with(write: { w: 0 }, database: "music") do |client|
client[:artists].find(...)
end

You can override the :read and :write options on a collection by using the with method. The following example shows how to use the with method to set the w write option to 0:

Band.collection.with(write: { w: 0 }) do |collection|
collection[:artists].find(...)
end

For more information about the methods mentioned in this guide, see the following API documentation:

Back

Application Configuration