123456789_123456789_123456789_123456789_123456789_

Class: Mongoid::Criteria

Relationships & Source Files
Namespace Children
Modules:
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
Inherits: Object
Defined in: lib/mongoid/criteria.rb,
lib/mongoid/criteria/findable.rb,
lib/mongoid/criteria/includable.rb,
lib/mongoid/criteria/inspectable.rb,
lib/mongoid/criteria/marshalable.rb,
lib/mongoid/criteria/modifiable.rb,
lib/mongoid/criteria/options.rb,
lib/mongoid/criteria/permission.rb,
lib/mongoid/criteria/queryable.rb,
lib/mongoid/criteria/scopable.rb,
lib/mongoid/criteria/translator.rb,
lib/mongoid/criteria/queryable/aggregable.rb,
lib/mongoid/criteria/queryable/expandable.rb,
lib/mongoid/criteria/queryable/key.rb,
lib/mongoid/criteria/queryable/macroable.rb,
lib/mongoid/criteria/queryable/mergeable.rb,
lib/mongoid/criteria/queryable/optional.rb,
lib/mongoid/criteria/queryable/options.rb,
lib/mongoid/criteria/queryable/pipeline.rb,
lib/mongoid/criteria/queryable/selectable.rb,
lib/mongoid/criteria/queryable/selector.rb,
lib/mongoid/criteria/queryable/smash.rb,
lib/mongoid/criteria/queryable/storable.rb,
lib/mongoid/criteria/queryable/extensions/array.rb,
lib/mongoid/criteria/queryable/extensions/big_decimal.rb,
lib/mongoid/criteria/queryable/extensions/boolean.rb,
lib/mongoid/criteria/queryable/extensions/date.rb,
lib/mongoid/criteria/queryable/extensions/date_time.rb,
lib/mongoid/criteria/queryable/extensions/hash.rb,
lib/mongoid/criteria/queryable/extensions/nil_class.rb,
lib/mongoid/criteria/queryable/extensions/numeric.rb,
lib/mongoid/criteria/queryable/extensions/object.rb,
lib/mongoid/criteria/queryable/extensions/range.rb,
lib/mongoid/criteria/queryable/extensions/regexp.rb,
lib/mongoid/criteria/queryable/extensions/set.rb,
lib/mongoid/criteria/queryable/extensions/string.rb,
lib/mongoid/criteria/queryable/extensions/symbol.rb,
lib/mongoid/criteria/queryable/extensions/time.rb,
lib/mongoid/criteria/queryable/extensions/time_with_zone.rb

Overview

The Criteria class is the core object needed in ::Mongoid to retrieve objects from the database. It is a DSL that essentially sets up the selector and options arguments that get passed on to a Mongo::Collection in the Ruby driver. Each method on the Criteria returns self to they can be chained in order to create a readable criterion to be executed against the database.

Constant Summary

Class Method Summary

Instance Attribute Summary

Clients::Options - Included

#persistence_context

Get the document’s current persistence context.

#persistence_context?

Returns whether a persistence context is set for the document or the document’s class.

Scopable - Included

#scoped?

Has the criteria had the default scope applied?

#scoping_options

Get the criteria scoping options, as a pair (scoped, unscoped).

#scoping_options=

::Set the criteria scoping options, as a pair (scoped, unscoped).

#unscoped

Clears all scoping from the criteria.

#unscoped?

Is the criteria unscoped?

Modifiable - Included

Includable - Included

#inclusions

Get a list of criteria that are to be executed for eager loading.

#inclusions=

::Set the inclusions for the criteria.

Queryable - Included

Criteria::Queryable::Optional - Included

Criteria::Queryable::Aggregable - Included

Criteria::Queryable::Mergeable - Included

Instance Method Summary

Options - Included

Clients::Sessions - Included

#ensure_client_compatibility!

If at least one session is active, this ensures that the current model’s client is compatible with one of them.

Clients::Options - Included

#collection

Get the collection for the document’s current persistence context.

#collection_name

Get the collection name for the document’s current persistence context.

#mongo_client

Get the database client for the document’s current persistence context.

#with

Change the persistence context for this object during the block.

#clear_persistence_context, #default_storage_options, #set_persistence_context

Scopable - Included

#apply_default_scope

Applies the default scope to the criteria.

#apply_scope

Applies a scope to the current criteria.

#remove_scoping

Given another criteria, remove the other criteria’s scoping from this criteria.

#scoped

Forces the criteria to be scoped, unless its inside an unscoped block.

#with_default_scope

Get the criteria with the default scope applied, if the default scope is able to be applied.

#reject_matching

Modifiable - Included

#build

Build a document given the selector and return it.

#create

Create a document in the database given the selector and return it.

#create!

Create a document in the database given the selector and return it.

#create_with

Define attributes with which new documents will be created.

#find_or_create_by

Find the first Document given the conditions, or creates a new document with the conditions that were supplied.

#find_or_create_by!

Find the first Document given the conditions, or creates a new document with the conditions that were supplied.

#find_or_initialize_by

Find the first Document given the conditions, or initializes a new document with the conditions that were supplied.

#first_or_create

Find the first Document, or creates a new document with the conditions that were supplied plus attributes.

#first_or_create!

Find the first Document, or creates a new document with the conditions that were supplied plus attributes and will raise an error if validation fails.

#first_or_initialize

Find the first Document, or initializes a new document with the conditions that were supplied plus attributes.

#new

Alias for Modifiable#build.

#create_document

Create a document given the provided method and attributes from the existing selector.

#find_or

Find the first object or create/initialize it.

#first_or

Find the first document or create/initialize it.

#invalid_embedded_doc?, #invalid_key?

Marshalable - Included

#marshal_dump

Provides the data needed to Marshal.dump a criteria.

#marshal_load

Resets the criteria object after a Marshal.load.

#dump_hash, #load_hash

Includable - Included

#includes

Eager loads all the provided associations.

#add_inclusion

Add an inclusion definition to the list of inclusions for the criteria.

#extract_includes_list

Iterate through the list of relations and create the inclusions list.

Inspectable - Included

#inspect

Get a pretty string representation of the criteria, including the selector, options, matching count and documents for inspection.

Findable - Included

#execute_or_raise

Execute the criteria or raise an error if no documents found.

#find

Find the matching document(s) in the criteria for the provided id(s).

#for_ids

Adds a criterion to the Criteria that specifies an id that must be matched.

#multiple_from_db

Get the documents from the identity map, and if not found hit the database.

#from_database

Get documents from the database only.

#from_database_selector,
#id_finder

Get the finder used to generate the id query.

#mongoize_ids

Convert all the ids to their proper types.

#multi_args?

Indicates whether the given arguments array is a list of values.

#prepare_ids_for_find

Convert args to the #find method into a flat array of ids.

#raise_invalid

Convenience method of raising an invalid find error.

Queryable - Included

#==

Is this queryable equal to another object? Is true if the selector and options are equal.

#initialize

Initialize the new queryable.

#initialize_copy

Handle the creation of a copy via #clone or #dup.

#to_mql

Returns selector and options of the criteria in form of MongoDB command.

Criteria::Queryable::Optional - Included

#asc
#ascending

Add ascending sorting options for all the provided fields.

#batch_size

Adds the option for telling MongoDB how many documents to retrieve in it’s batching.

#collation

::Set the collation.

#comment

Associate a comment with the query.

#cursor_type

::Set the cursor type.

#desc
#descending

Add descending sorting options for all the provided fields.

#hint

Add an index hint to the query options.

#limit

Add the number of documents to limit in the returned results.

#max_scan

Adds the option to limit the number of documents scanned in the collection.

#max_time_ms

Adds a cumulative time limit in milliseconds for processing operations on a cursor.

#no_timeout

Tell the query not to timeout.

#offset
#only

Limits the results to only contain the fields provided.

#order
#order_by

Adds sorting criterion to the options.

#reorder

Instead of merging the order criteria, use this method to completely replace the existing ordering with the provided.

#skip

Add the number of documents to skip.

#slice

Limit the returned results via slicing embedded arrays.

#snapshot

Tell the query to operate in snapshot mode.

#without

Limits the results to only contain the fields not provided.

#add_sort_option

Add a single sort option.

#option

Take the provided criterion and store it as an option in the query options.

#sort_with_list

Add multiple sort options at once.

Selectable - Included

#atomic_selector

Get the atomic selector for the document.

#embedded_atomic_selector

Get the atomic selector for an embedded document.

#root_atomic_selector_in_db

Get the atomic selector that would match the existing version of the root document.

Criteria::Queryable::Aggregable - Included

#group

Add a group ($group) operation to the aggregation pipeline.

#project

Add a projection ($project) to the aggregation pipeline.

#unwind

Add an unwind ($unwind) to the aggregation pipeline.

#aggregation

Add the aggregation operation.

Criteria::Queryable::Mergeable - Included

#and_with_operator

Merge criteria with operators using the and operator.

#intersect

Instruct the next mergeable call to use intersection.

#override

Instruct the next mergeable call to use override.

#reset_strategies!

Clear the current strategy and negating flag, used after cloning.

#union

Instruct the next mergeable call to use union.

#__add__

Adds the criterion to the existing selection.

#__expanded__

Adds the criterion to the existing selection.

#__intersect__

Adds the criterion to the existing selection.

#__merge__

Perform a straight merge of the criterion into the selection and let the symbol overrides do all the work.

#__multi__

Adds $and/$or/$nor criteria to a copy of this selection.

#__override__

Adds the criterion to the existing selection.

#__union__

Adds the criterion to the existing selection.

#_mongoid_add_top_level_operation

Combines criteria into a MongoDB selector.

#_mongoid_expand_keys

Takes a criteria hash and expands Key objects into hashes containing MQL corresponding to said key objects.

#_mongoid_flatten_arrays

Calling .flatten on an array which includes a Criteria instance evaluates the criteria, which we do not want.

#prepare

Prepare the value for merging.

#use

Use the named strategy for the next operation.

#with_strategy

Add criterion to the selection with the named strategy.

Criteria::Queryable::Expandable - Included

#expand_condition_to_array_values

Expand criterion values to arrays, to be used with operators that take an array as argument such as $in.

#expand_one_condition

Expands the specified condition to MongoDB syntax.

Criteria::Queryable::Storable - Included

#add_field_expression

Adds a field expression to the query.

#add_logical_operator_expression

Adds a logical operator expression to the selector.

#add_one_expression

Adds an arbitrary expression to the query.

#add_operator_expression

Adds an operator expression to the selector.

Contextual - Included

#context

Get the context in which criteria queries should execute.

#load_async

Instructs the context to schedule an asynchronous loading of documents specified by the criteria.

#create_context

Create the context for the queries to execute.

Constructor Details

.new(klass) ⇒ Criteria

Initialize the new criteria.

Examples:

Init the new criteria.

Criteria.new(Band)

Parameters:

  • klass (Class)

    The model class.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 294

def initialize(klass)
  @klass = klass
  @embedded = nil
  @none = nil
  klass ? super(klass.aliased_fields, klass.fields, klass.relations, klass.aliased_associations) : super({}, {}, {}, {})
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missingObject (private)

Used for chaining Criteria scopes together in the for of class methods on the Document the criteria is for.

Examples:

Handle method missing.

criteria.method_missing(:name)

Parameters:

  • name (Symbol)

    The method name.

  • *args (Object...)

    The arguments.

Returns:

  • (Object)

    The result of the method call.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 593

ruby2_keywords def method_missing(name, *args, &block)
  if klass.respond_to?(name)
    klass.send(:with_scope, self) do
      klass.send(name, *args, &block)
    end
  elsif CHECK.respond_to?(name)
    return entries.send(name, *args, &block)
  else
    super
  end
end

Class Method Details

.from_hash(hash) ⇒ Criteria

Convert the given hash to a criteria. Will iterate over each keys in the hash which must correspond to method on a criteria object. The hash must also include a “klass” key.

Examples:

Convert the hash to a criteria.

Criteria.from_hash({ klass: Band, where: { name: "Depeche Mode" })

Parameters:

  • hash (Hash)

    The hash to convert.

Returns:

  • (Criteria)

    The criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 55

def from_hash(hash)
  criteria = Criteria.new(hash.delete(:klass) || hash.delete('klass'))
  hash.each_pair do |method, args|
    criteria = criteria.__send__(method, args)
  end
  criteria
end

Instance Attribute Details

#_raw_resultsnil | Hash (rw)

This method is for internal use only.

An internal helper for getting/setting the “raw” flag on a given criteria object.

Returns:

  • (nil | Hash)

    If set, it is a hash with two keys, :raw and :typed, that describe whether raw results should be returned, and whether they ought to be typecast.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 215

attr_accessor :_raw_results

#association (rw)

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 68

attr_accessor :embedded, :klass, :parent_document, :association

#documentsArray<Document> (rw)

Get the documents from the embedded criteria.

Examples:

Get the documents.

criteria.documents

Returns:

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 150

def documents
  @documents ||= []
end

#documents=(docs) ⇒ Array<Document> (rw)

::Set the embedded documents on the criteria.

Examples:

::Set the documents.

Parameters:

Returns:

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 161

def documents=(docs)
  @documents = docs
end

#embedded (rw)

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 68

attr_accessor :embedded, :klass, :parent_document, :association

#embedded?true | false (rw)

Is the criteria for embedded documents?

Examples:

Is the criteria for embedded documents?

criteria.embedded?

Returns:

  • (true | false)

    If the criteria is embedded.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 171

def embedded?
  !!@embedded
end

#empty_and_chainable?true | false (readonly)

Is the criteria an empty but chainable criteria?

Examples:

Is the criteria a none criteria?

criteria.empty_and_chainable?

Returns:

  • (true | false)

    If the criteria is a none.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 363

def empty_and_chainable?
  !!@none
end

#klass (rw)

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 68

attr_accessor :embedded, :klass, :parent_document, :association

#parent_document (rw)

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 68

attr_accessor :embedded, :klass, :parent_document, :association

#raw_results?true | false (readonly)

Predicate that answers the question: is this criteria object currently in raw mode? (See #raw for a description of raw mode.)

Returns:

  • (true | false)

    whether the criteria is in raw mode or not.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 221

def raw_results?
  _raw_results && _raw_results[:raw]
end

#type_selectable?true | false (readonly, private)

This method is for internal use only.

Is the criteria type selectable?

Examples:

If the criteria type selectable?

criteria.type_selectable?

Returns:

  • (true | false)

    If type selection should be added.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 624

def type_selectable?
  klass.hereditary? &&
    !selector.keys.include?(self.discriminator_key) &&
    !selector.keys.include?(self.discriminator_key.to_sym)
end

#typecast_results?true | false (readonly)

Predicate that answers the question: should the results returned by this criteria object be typecast? (See #raw for a description of this.) The answer is meaningless unless #raw_results? is true, since if instantiated document objects are returned they will always be typecast.

Returns:

  • (true | false)

    whether the criteria should return typecast results.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 232

def typecast_results?
  _raw_results && _raw_results[:typed]
end

Instance Method Details

#==(other) ⇒ true | false

Note:

This will force a database load when called if an enumerable is passed.

Returns true if the supplied Enumerable or Criteria is equal to the results of this Criteria or the criteria itself.

Parameters:

  • other (Object)

    The other Enumerable or Criteria to compare to.

Returns:

  • (true | false)

    If the objects are equal.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 78

def ==(other)
  return super if other.respond_to?(:selector)
  entries == other
end

#_enumerable_find

This method is for internal use only.
[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 26

alias :_enumerable_find :find

#_findable_find

This method is for internal use only.
[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 33

alias :_findable_find :find

#as_json(options = nil) ⇒ String

Needed to properly get a criteria back as json

Examples:

Get the criteria as json.

Person.where(:title => "Sir").as_json

Parameters:

Returns:

  • (String)

    The JSON string.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 140

def as_json(options = nil)
  entries.as_json(options)
end

#check_for_missing_documents!(result, ids) (private)

This method is for internal use only.

Are documents in the query missing, and are we configured to raise an error?

Examples:

Check for missing documents.

criteria.check_for_missing_documents!([], [ 1 ])

Parameters:

Raises:

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 554

def check_for_missing_documents!(result, ids)
  if (result.size < ids.size) && Mongoid.raise_not_found_error
    raise Errors::DocumentNotFound.new(klass, ids, ids - result.map(&:_id))
  end
end

#extract_idObject

Extract a single id from the provided criteria. Could be in an $and query or a straight _id query.

Examples:

Extract the id.

criteria.extract_id

Returns:

  • (Object)

    The id.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 243

def extract_id
  selector['_id'] || selector[:_id] || selector['id'] || selector[:id]
end

#extras(extras) ⇒ Criteria

Adds a criterion to the Criteria that specifies additional options to be passed to the Ruby driver, in the exact format for the driver.

criteria.extras(:limit => 20, :skip => 40)

Examples:

Add extra params to the criteria.

Parameters:

  • extras (Hash)

    The extra driver options.

Returns:

  • (Criteria)

    The cloned criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 256

def extras(extras)
  crit = clone
  crit.options.merge!(extras)
  crit
end

#field_listArray<String>

Get the list of included fields.

Examples:

Get the field list.

criteria.field_list

Returns:

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 268

def field_list
  if options[:fields]
    options[:fields].keys.reject{ |key| key == klass.discriminator_key }
  else
    []
  end
end

#find(*args) {|Object| ... } ⇒ Document | Array<Document> | nil

Note:

Each argument can be an individual id, an array of ids or a nested array. Each array will be flattened.

Finds one or many documents given the provided _id values, or filters the documents in the current scope in the application process space after loading them if needed.

If this method is not given a block, it delegates to Findable#find and finds one or many documents for the provided _id values.

If this method is given a block, it delegates to Enumerable#find and returns the first document of those found by the current Crieria object for which the block returns a truthy value.

Note that the “default proc” argument of Enumerable is not specially treated by ::Mongoid - the decision between delegating to Criteria::Findable vs Enumerable is made solely based on whether find is passed a block.

Examples:

Finds a document by its _id, invokes Findable#find.

critera.find("1234")

Finds the first matching document using a block, invokes Enumerable#find.

criteria.find { |item| item.name == "Depeche Mode" }

Finds the first matching document using a block using the default Proc, invokes Enumerable#find.

criteria.find(-> { "Default Band" }) { |item| item.name == "Milwaukee Mode" }

Tries to find a document whose _id is the stringification of the provided Proc, typically failing.

enumerator = criteria.find(-> { "Default Band" })

Parameters:

  • *args ([ Object | Array<Object> ]...)

    The id(s).

  • &block

    Optional block to pass.

Yields:

  • (Object)

    Yields each enumerable element to the block.

Returns:

Raises:

See Also:

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 124

def find(*args, &block)
  if block_given?
    _enumerable_find(*args, &block)
  else
    _findable_find(*args)
  end
end

#for_js(javascript, scope = {}) ⇒ Criteria

Deprecated.

Find documents by the provided javascript and scope. Uses a $where but is different from #where in that it will pass a code object to the query instead of a pure string. Safe against Javascript injection attacks.

Examples:

Find by javascript.

Band.for_js("this.name = param", param: "Tool")

Parameters:

  • javascript (String)

    The javascript to execute in the $where.

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

    The scope for the code.

Returns:

  • (Criteria)

    The criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 528

def for_js(javascript, scope = {})
  code = if scope.empty?
    # CodeWithScope is not supported for $where as of MongoDB 4.4
    BSON::Code.new(javascript)
  else
    BSON::CodeWithScope.new(javascript, scope)
  end
  js_query(code)
end

#freezeCriteria

When freezing a criteria we need to initialize the context first otherwise the setting of the context on attempted iteration will raise a runtime error.

Examples:

Freeze the criteria.

criteria.freeze

Returns:

  • (Criteria)

    The frozen criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 284

def freeze
  context and inclusions and super
end

#initialize_copy(other) ⇒ nil (private)

This method is for internal use only.

Clone or dup the current Criteria. This will return a new criteria with the selector, options, klass, embedded options, etc intact.

Examples:

Clone a criteria.

criteria.clone

Dup a criteria.

criteria.dup

Parameters:

  • other (Criteria)

    The criteria getting cloned.

Returns:

  • (nil)

    nil.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 574

def initialize_copy(other)
  @inclusions = other.inclusions.dup
  @scoping_options = other.scoping_options
  @documents = other.documents.dup
  self._raw_results = other._raw_results
  @context = nil
  super
end

#merge(other) ⇒ Criteria

Merges another object with this Criteria and returns a new criteria. The other object may be a Criteria or a ::Hash. This is used to combine multiple scopes together, where a chained scope situation may be desired.

Examples:

Merge the criteria with another criteria.

criteria.merge(other_criteria)

Merge the criteria with a hash. The hash must contain a klass

key and the key/value pairs correspond to method names/args.

criteria.merge({
  klass: Band,
  where: { name: "Depeche Mode" },
  order_by: { name: 1 }
})

Parameters:

  • other (Criteria)

    The other criterion to merge with.

Returns:

  • (Criteria)

    A cloned self.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 321

def merge(other)
  crit = clone
  crit.merge!(other)
  crit
end

#merge!(other) ⇒ Criteria

Merge the other criteria into this one.

Examples:

Merge another criteria into this criteria.

criteria.merge(Person.where(name: "bob"))

Parameters:

  • other (Criteria | Hash)

    The criteria to merge in.

Returns:

  • (Criteria)

    The merged criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 335

def merge!(other)
  other = self.class.from_hash(other) if other.is_a?(Hash)
  selector.merge!(other.selector)
  options.merge!(other.options)
  self.documents = other.documents.dup unless other.documents.empty?
  self.scoping_options = other.scoping_options
  self.inclusions = (inclusions + other.inclusions).uniq
  self._raw_results = self._raw_results || other._raw_results
  self
end

#merge_type_selectiontrue | false (private)

For models where inheritance is at play we need to add the type selection.

Examples:

Add the type selection.

criteria.merge_type_selection

Returns:

  • (true | false)

    If type selection was added.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 612

def merge_type_selection
  selector.merge!(type_selection) if type_selectable?
end

#noneCriteria

Returns a criteria that will always contain zero results and never hits the database.

Examples:

Return a none criteria.

criteria.none

Returns:

  • (Criteria)

    The none criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 353

def none
  @none = true and self
end

#only(*args) ⇒ Criteria

Overriden to include _type in the fields.

Examples:

Limit the fields returned from the database.

Band.only(:name)

Parameters:

Returns:

  • (Criteria)

    The cloned criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 375

def only(*args)
  args = args.flatten
  return clone if args.empty?
  if (args & Fields::IDS).empty?
    args.unshift(:_id)
  end
  if klass.hereditary?
    args.push(klass.discriminator_key.to_sym)
  end
  super(*args)
end

#raw(raw_results = true, typed: nil) ⇒ Criteria

Produce a clone of the current criteria object with it’s “raw” setting set to the given value. A criteria set to “raw” will return all results as raw hashes. If typed is true, the values in the hashes will be typecast according to the fields that they correspond to.

When “raw” is not set (or if raw_results is false), the criteria will return all results as instantiated Document instances.

Examples:

Return query results as raw hashes:

Person.where(city: 'Boston').raw

Parameters:

  • raw_results (true | false) (defaults to: true)

    Whether the new criteria should be placed in “raw” mode or not.

  • typed (true | false)

    Whether the raw results should be typecast before being returned. Default is true if raw_results is false, and false otherwise.

Returns:

  • (Criteria)

    the cloned criteria object.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 193

def raw(raw_results = true, typed: nil)
  # default for typed is true when raw_results is false, and false when
  # raw_results is true.
  typed = !raw_results if typed.nil?

  if !typed && !raw_results
    raise ArgumentError, 'instantiated results must be typecast'
  end

  clone.tap do |criteria|
    criteria._raw_results = { raw: raw_results, typed: typed }
  end
end

#read(value = nil) ⇒ Criteria

::Set the read preference for the criteria.

Examples:

::Set the read preference.

criteria.read(mode: :primary_preferred)

Parameters:

  • value (Hash) (defaults to: nil)

    The mode preference.

Returns:

  • (Criteria)

    The cloned criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 395

def read(value = nil)
  clone.tap do |criteria|
    criteria.options.merge!(read: value)
  end
end

#respond_to?(name, include_private = false) ⇒ true | false

Returns true if criteria responds to the given method.

Examples:

Does the criteria respond to the method?

crtiteria.respond_to?(:each)

Parameters:

  • name (Symbol)

    The name of the class method on the Document.

  • include_private (true | false) (defaults to: false)

    Whether to include privates.

Returns:

  • (true | false)

    If the criteria responds to the method.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 423

def respond_to?(name, include_private = false)
  super || klass.respond_to?(name) || CHECK.respond_to?(name, include_private)
end

#selector_with_type_selectionHash (private)

This method is for internal use only.

Get a new selector with type selection in it.

Examples:

Get a selector with type selection.

criteria.selector_with_type_selection

Returns:

  • (Hash)

    The selector.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 655

def selector_with_type_selection
  type_selectable? ? selector.merge(type_selection) : selector
end

#to_ary

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 427

alias :to_ary :to_a

#to_criteriaCriteria

Deprecated.

Convenience for objects that want to be merged into a criteria.

Examples:

Convert to a criteria.

criteria.to_criteria

Returns:

  • (Criteria)

    self.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 436

def to_criteria
  self
end

#to_procProc

Convert the criteria to a proc.

Examples:

Convert the criteria to a proc.

criteria.to_proc

Returns:

  • (Proc)

    The wrapped criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 447

def to_proc
  ->{ self }
end

#type(types) ⇒ Criteria

Adds a criterion to the Criteria that specifies a type or an ::Array of types that must be matched.

Examples:

Match only specific models.

criteria.type('Browser')
criteria.type(['Firefox', 'Browser'])

Parameters:

  • types (Array<String>)

    The types to match against.

Returns:

  • (Criteria)

    The cloned criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 461

def type(types)
  any_in(self.discriminator_key.to_sym => Array(types))
end

#type_selectionHash (private)

This method is for internal use only.

Get the selector for type selection.

Examples:

Get a type selection hash.

criteria.type_selection

Returns:

  • (Hash)

    The type selection.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 638

def type_selection
  klasses = klass._types
  if klasses.size > 1
    { klass.discriminator_key.to_sym => { "$in" => klass._types }}
  else
    { klass.discriminator_key.to_sym => klass._types[0] }
  end
end

#where(*args) ⇒ Criteria

This is the general entry point for most MongoDB queries. This either creates a standard field: value selection, and expanded selection with the use of hash methods, or a $where selection if a string is provided.

Examples:

Add a standard selection.

criteria.where(name: "syd")

Add a javascript selection.

criteria.where("this.name == 'syd'")

Parameters:

  • *args ([ Hash | String ]...)

    The standard selection or javascript string.

Returns:

  • (Criteria)

    The cloned selectable.

Raises:

  • (UnsupportedJavascript)

    If provided a string and the criteria is embedded.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 482

def where(*args)
  # Historically this method required exactly one argument.
  # As of https://jira.mongodb.org/browse/MONGOID-4804 it also accepts
  # zero arguments.
  # The underlying where implemetation that super invokes supports
  # any number of arguments, but we don't presently allow mutiple
  # arguments through this method. This API can be reconsidered in the
  # future.
  if args.length > 1
    raise ArgumentError, "Criteria#where requires zero or one arguments (given #{args.length})"
  end
  if args.length == 1
    expression = args.first
    if expression.is_a?(::String) && embedded?
      raise Errors::UnsupportedJavascript.new(klass, expression)
    end
  end
  super
end

#without(*args) ⇒ Criteria

Overriden to exclude _id from the fields.

Examples:

Exclude fields returned from the database.

Band.without(:name)

Parameters:

  • *args (Symbol...)

    The field name(s).

Returns:

  • (Criteria)

    The cloned criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 409

def without(*args)
  args -= id_fields
  super(*args)
end

#without_optionsCriteria

Get a version of this criteria without the options.

Examples:

Get the criteria without options.

criteria.without_options

Returns:

  • (Criteria)

    The cloned criteria.

[ GitHub ]

  
# File 'lib/mongoid/criteria.rb', line 508

def without_options
  crit = clone
  crit.options.clear
  crit
end