Module: Mongoid::Indexable::ClassMethods

Defined in:
lib/mongoid/indexable.rb

Instance Method Summary collapse

Instance Method Details

#add_indexestrue

Add the default indexes to the root document if they do not already exist. Currently this is only _type.

Examples:

Add Mongoid internal indexes.

Person.add_indexes

Returns:

  • If the operation succeeded.



52
53
54
55
56
57
# File 'lib/mongoid/indexable.rb', line 52

def add_indexes
  if hereditary? && !index_keys.include?(discriminator_key.to_sym => 1)
    index({ discriminator_key.to_sym => 1 }, unique: false, background: true)
  end
  true
end

#create_indexestrue

Send the actual index creation comments to the MongoDB driver

Examples:

Create the indexes for the class.

Person.create_indexes

Returns:

  • If the operation succeeded.



24
25
26
27
28
29
30
# File 'lib/mongoid/indexable.rb', line 24

def create_indexes
  return unless index_specifications

  Threaded.with_collection_management do
    perform_create_indexes
  end
end

#index(spec, options = nil) ⇒ Hash

Adds an index definition for the provided single or compound keys.

Examples:

Create a basic index.

class Person
  include Mongoid::Document
  field :name, type: String
  index({ name: 1 }, { background: true })
end

Parameters:

  • The index spec.

  • (defaults to: nil)

    The index options.

Returns:

  • The index options.



72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/mongoid/indexable.rb', line 72

def index(spec, options = nil)
  specification = Specification.new(self, spec, options)

  # the equality test for Indexable::Specification instances does not
  # consider any options, which means names are not compared. This means
  # that an index with different options from another, and a different
  # name, will be silently ignored unless duplicate index declarations
  # are allowed.
  return unless Mongoid.allow_duplicate_index_declarations || !index_specifications.include?(specification)

  index_specifications.push(specification)
end

#index_specification(index_hash, index_name = nil) ⇒ Specification

Get an index specification for the provided key.

Examples:

Get the index specification.

Model.index_specification(name: 1)

Parameters:

  • The index key/direction pair.

  • (defaults to: nil)

    The index name.

Returns:

  • The found specification.



94
95
96
97
98
# File 'lib/mongoid/indexable.rb', line 94

def index_specification(index_hash, index_name = nil)
  index_specifications.detect do |spec|
    spec.superficial_match?(key: index_hash, name: index_name)
  end
end

#remove_indexestrue

Send the actual index removal comments to the MongoDB driver, but lets _id untouched.

Examples:

Remove the indexes for the class.

Person.remove_indexes

Returns:

  • If the operation succeeded.



39
40
41
42
43
# File 'lib/mongoid/indexable.rb', line 39

def remove_indexes
  Threaded.with_collection_management do
    perform_remove_indexes
  end
end