Module: Mongoid::Fields::ClassMethods

Defined in:
lib/mongoid/fields.rb,
lib/mongoid/fields.rb

Instance Method Summary collapse

Instance Method Details

#attribute_namesArray<String>

Returns an array of names for the attributes available on this object.

Provides the field names in an ORM-agnostic way. Rails v3.1+ uses this method to automatically wrap params in JSON requests.

Examples:

Get the field names

Model.attribute_names

Returns:

  • (Array<String>)

    The field names



449
450
451
# File 'lib/mongoid/fields.rb', line 449

def attribute_names
  fields.keys
end

#auto_embed_field(name, model: 'voyage-4', num_dimensions: nil, quantization: nil, similarity: nil, index: nil) ⇒ Object

Declares a text field and registers a corresponding Atlas Vector Search index for it using the auto-embedding (autoEmbed) type. Atlas generates the embeddings automatically at index and query time; no pre-computed vectors are required.

Examples:

Minimal declaration.

class Article
  include Mongoid::Document
  auto_embed_field :description
end

With all options.

class Article
  include Mongoid::Document
  auto_embed_field :description,
                   model: 'voyage-4',
                   num_dimensions: 512,
                   quantization: 'binary',
                   similarity: 'cosine',
                   index: :article_embed
end

Parameters:

  • name (Symbol | String)

    The name of the text field to declare and auto-embed.

  • model (String) (defaults to: 'voyage-4')

    The embedding model name. Defaults to 'voyage-4' (recommended). Supported values at Public Preview: voyage-4-large, voyage-4, voyage-4-lite, voyage-code-3.

  • num_dimensions (Integer | nil) (defaults to: nil)

    Number of vector dimensions. Supported values: 256, 512, 1024, 2048. Default: 1024.

  • quantization (String | nil) (defaults to: nil)

    Quantization type: float, scalar, binary, or binaryNoRescore. Default: scalar.

  • similarity (String | nil) (defaults to: nil)

    Similarity function: dotProduct, cosine, or euclidean.

  • index (Symbol | String | nil) (defaults to: nil)

    The index name. If omitted the index is unnamed and Atlas calls it 'default'.



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/mongoid/fields.rb', line 542

def auto_embed_field(name, model: 'voyage-4', num_dimensions: nil, quantization: nil, similarity: nil, index: nil)
  field(name, type: String)

  field_spec = {
    type: 'autoEmbed',
    modality: 'text',
    path: name.to_s,
    model: model
  }
  field_spec[:numDimensions] = num_dimensions if num_dimensions
  field_spec[:quantization]  = quantization  if quantization
  field_spec[:similarity]    = similarity    if similarity

  if index
    vector_search_index(index, fields: [ field_spec ])
  else
    vector_search_index(fields: [ field_spec ])
  end
end

#cleanse_localized_field_names(name) ⇒ Field

Removes the _translations from the given field name. This is done only when there doesn't already exist a field name or relation with the same name (i.e. with the _translations suffix). This check for an existing field is done recursively

Parameters:

  • name (String | Symbol)

    The name of the field to cleanse.

Returns:

  • (Field)

    The field name without _translations



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/mongoid/fields.rb', line 98

def cleanse_localized_field_names(name)
  name = database_field_name(name.to_s)

  klass = self
  [].tap do |res|
    ar = name.split('.')
    ar.each_with_index do |fn, i|
      key = fn
      unless klass.fields.key?(fn) || klass.relations.key?(fn)
        key = if fn.end_with?(TRANSLATIONS_SFX)
                fn.delete_suffix(TRANSLATIONS_SFX)
              else
                fn
              end

      end
      res.push(key)

      if klass.fields.key?(fn)
        res.push(ar.drop(i + 1).join('.')) unless i == ar.length - 1
        break
      elsif klass.relations.key?(fn)
        klass = klass.relations[key].klass
      end
    end
  end.join('.')
end

#database_field_name(name) ⇒ String

Get the name of the provided field as it is stored in the database. Used in determining if the field is aliased or not.

Parameters:

  • name (String | Symbol)

    The name to get.

Returns:

  • (String)

    The name of the field as it's stored in the db.



459
460
461
# File 'lib/mongoid/fields.rb', line 459

def database_field_name(name)
  Fields.database_field_name(name, relations, aliased_fields, aliased_associations)
end

#extract_id_field(attributes) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Extracts the id field from the specified attributes hash based on aliases defined in this class.

Parameters:

  • attributes (Hash)

    The attributes to inspect.

Returns:

  • (Object)

    The id value.



81
82
83
84
85
86
87
88
# File 'lib/mongoid/fields.rb', line 81

def extract_id_field(attributes)
  id_fields.each do |k|
    if v = attributes[k]
      return v
    end
  end
  nil
end

#field(name, options = {}) ⇒ Field

Defines all the fields that are accessible on the Document For each field that is defined, a getter and setter will be added as an instance method to the Document.

Examples:

Define a field.

field :score, type: Integer, default: 0

Parameters:

  • name (Symbol)

    The name of the field.

  • options (Hash) (defaults to: {})

    The options to pass to the field.

Options Hash (options):

  • :type (Class | Symbol | String)

    The type of the field.

  • :label (String)

    The label for the field.

  • :default (Object | Proc)

    The field's default.

Returns:

  • (Field)

    The generated field



577
578
579
580
581
582
583
584
585
# File 'lib/mongoid/fields.rb', line 577

def field(name, options = {})
  named = name.to_s
  Validators::Macro.validate(self, name, options)
  added = add_field(named, options)
  descendants.each do |subclass|
    subclass.add_field(named, options)
  end
  added
end

#id_fieldsArray<Symbol | String>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the list of id fields for this model class, as both strings and symbols.

Returns:

  • (Array<Symbol | String>)

    List of id fields.



62
63
64
65
66
67
68
69
70
71
# File 'lib/mongoid/fields.rb', line 62

def id_fields
  IDS.dup.tap do |id_fields|
    aliased_fields.each do |k, v|
      if v == '_id'
        id_fields << k.to_sym
        id_fields << k
      end
    end
  end
end

#replace_field(name, type) ⇒ Serializable

Replace a field with a new type.

Examples:

Replace the field.

Model.replace_field("_id", String)

Parameters:

  • name (String)

    The name of the field.

  • type (Class)

    The new type of field.

Returns:



596
597
598
599
# File 'lib/mongoid/fields.rb', line 596

def replace_field(name, type)
  remove_defaults(name)
  add_field(name, fields[name].options.merge(type: type))
end

#traverse_association_tree(key) {|The, The, Whether| ... } ⇒ Field

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Traverse down the association tree and search for the field for the given key.

Parameters:

  • key (String)

    The key used to search the association tree.

  • &block

    The block.

Yield Parameters:

  • The (Symbol)

    current method.

  • The (Symbol | String)

    field or the relation.

  • Whether (true | false)

    the second yield parameter is a field or not.

Returns:

  • (Field)

    The field found for the given key at the end of the search. This will return nil if the last thing found is an association or no field was found for the given key.



627
628
629
# File 'lib/mongoid/fields.rb', line 627

def traverse_association_tree(key, &block)
  Fields.traverse_association_tree(key, fields, relations, aliased_associations, &block)
end

#using_object_ids?true | false

Convenience method for determining if we are using BSON::ObjectIds as our id.

Examples:

Does this class use object ids?

person.using_object_ids?

Returns:

  • (true | false)

    If the class uses BSON::ObjectIds for the id.



608
609
610
# File 'lib/mongoid/fields.rb', line 608

def using_object_ids?
  fields['_id'].object_id_field?
end

#vector_field(name, dimensions:, similarity: 'cosine', index: nil) ⇒ Object

Declares a vector embedding field and registers a corresponding Atlas Vector Search index for it in one step.

The field is stored as an Array. For advanced index options (quantization, indexing method, HNSW tuning) use the explicit field + vector_search_index combination instead.

Examples:

Minimal declaration.

class Article
  include Mongoid::Document
  vector_field :embedding, dimensions: 1536
end

With all options.

class Article
  include Mongoid::Document
  vector_field :embedding, dimensions: 1536,
                           similarity: 'dotProduct',
                           index: :article_vectors
end

Parameters:

  • name (Symbol | String)

    The name of the embedding field.

  • dimensions (Integer)

    The number of vector dimensions. Required.

  • similarity (String) (defaults to: 'cosine')

    The similarity metric to use: 'cosine' (default), 'euclidean', or 'dotProduct'.

  • index (Symbol | String | nil) (defaults to: nil)

    The name for the vector search index. If omitted the index is unnamed and Atlas calls it 'default'.



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/mongoid/fields.rb', line 490

def vector_field(name, dimensions:, similarity: 'cosine', index: nil)
  field(name, type: Array)

  field_spec = {
    type: 'vector',
    path: name.to_s,
    numDimensions: dimensions,
    similarity: similarity
  }

  if index
    vector_search_index(index, fields: [ field_spec ])
  else
    vector_search_index(fields: [ field_spec ])
  end
end