Module: Mongoid::Indexes::ClassMethods

Defined in:
lib/mongoid/indexes.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:

  • (true)

    If the operation succeeded.

Since:

  • 1.0.0



64
65
66
67
68
69
# File 'lib/mongoid/indexes.rb', line 64

def add_indexes
  if hereditary? && !index_options[{ _type: 1 }]
    index({ _type: 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:

  • (true)

    If the operation succeeded.

Since:

  • 1.0.0



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mongoid/indexes.rb', line 23

def create_indexes
  return unless index_options
  index_options.each_pair do |spec, options|
    if database = options[:database]
      with(consistency: :strong, database: database).
        collection.indexes.create(spec, options.except(:database))
    else
      with(consistency: :strong).collection.indexes.create(spec, options)
    end
  end and true
end

#index(spec, options = nil) ⇒ Hash

index({ name: 1 }, { background: true })

end

Parameters:

  • name (Symbol)

    The name of the field.

  • options (Hash) (defaults to: nil)

    The index options.

Returns:

  • (Hash)

    The index options.

Since:

  • 1.0.0



88
89
90
91
# File 'lib/mongoid/indexes.rb', line 88

def index(spec, options = nil)
  Validators::Options.validate(self, spec, options || {})
  index_options[normalize_spec(spec)] = normalize_index_options(options)
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:

  • (true)

    If the operation succeeded.

Since:

  • 3.0.0



44
45
46
47
48
49
50
51
52
53
# File 'lib/mongoid/indexes.rb', line 44

def remove_indexes
  indexed_database_names.each do |database|
    collection = with(consistency: :strong, database: database).collection
    collection.indexes.each do |spec|
      unless spec["name"] == "_id_"
        collection.indexes.drop(spec["key"])
      end
    end
  end and true
end