Docs Menu

Docs HomeMongoid


On this page

  • validates_uniqueness_of and :conditions Option
  • Read preference with validates_uniqueness_of

Mongoid includes ActiveModel::Validations to supply the basic validation plus an additional associated and uniqueness validator.

See the Active Record Validations Rails guide and ActiveModel::Validations documentation for more information.

Mongoid behaves slightly differently to Active Record when using #valid? on already persisted data. Active Record's #valid? will run all validations whereas Mongoid's #valid? will only run validations on documents that are in memory as an optimization.

The :conditions option to validates_uniqueness_of can be used to provide additional conditions to add to the database query looking for identical documents. This option does not influence when the validation is executed because it is not considered when Mongoid retrieves the present value of the respective field from the model. Consider the following example:

class Band
include Mongoid::Document
field :name, type: String
field :year, type: Integer
validates_uniqueness_of :name, conditions: -> { where(:year.gte => 2000) }
# OK
Band.create!(name: "Sun Project", year: 2000)
# Fails validation because there is a band with the "Sun Project" name
# and year 2000 in the database, even though the model being created now
# does not have a year.
Band.create!(name: "Sun Project")

In order to validate the uniqueness of an attribute, Mongoid must check that the value for that attribute does not already exist in the database. If Mongoid queries a secondary member of the replica set, there is a possibility that it is reading stale data. Because of this, the queries used to check a validates_uniqueness_of validation always use read preference primary.

←  AssociationsCollection Configuration →
Share Feedback
© 2023 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.