123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Shardable::ClassMethods

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Extended In:
Defined in: lib/mongoid/shardable.rb

Instance Method Summary

Instance Method Details

#shard_key(*args)

Specifies a shard key with the field(s) specified.

Examples:

Specify the shard key.

class Person
  include Mongoid::Document
  field :first_name, :type => String
  field :last_name, :type => String

  shard_key first_name: 1, last_name: 1
end
[ GitHub ]

  
# File 'lib/mongoid/shardable.rb', line 120

def shard_key(*args)
  unless args.first.is_a?(Hash)
    # Shorthand syntax
    if args.last.is_a?(Hash)
      raise ArgumentError, 'Shorthand shard_key syntax does not permit options'
    end

    spec = Hash[args.map do |name|
      [name, 1]
    end]

    return shard_key(spec)
  end

  if args.length > 2
    raise ArgumentError, 'Full shard_key syntax requires 1 or 2 arguments'
  end

  spec, options = args

  spec = Hash[spec.map do |name, value|
    if value.is_a?(Symbol)
      value = value.to_s
    end
    [database_field_name(name).to_sym, value]
  end]

  self.shard_key_fields = spec.keys
  self.shard_config = {
    key: spec.freeze,
    options: (options || {}).dup.freeze,
  }.freeze
end