Class: Mongoid::Criteria
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
-
CHECK =
Static array used to check with method missing - we only need to ever instantiate once.
[]
Class Method Summary
-
.from_hash(hash) ⇒ Criteria
Convert the given hash to a criteria.
-
.new(klass) ⇒ Criteria
constructor
Initialize the new criteria.
Instance Attribute Summary
-
#_raw_results ⇒ nil | Hash
rw
Internal use only
Internal use only
An internal helper for getting/setting the “raw” flag on a given criteria object.
- #association rw
-
#documents ⇒ Array<Document>
rw
Get the documents from the embedded criteria.
-
#documents=(docs) ⇒ Array<Document>
rw
::Set
the embedded documents on the criteria. - #embedded rw
-
#embedded? ⇒ true | false
rw
Is the criteria for embedded documents?
-
#empty_and_chainable? ⇒ true | false
readonly
Is the criteria an empty but chainable criteria?
- #klass rw
- #parent_document rw
-
#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.).
-
#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.
-
#type_selectable? ⇒ true | false
readonly
private
Internal use only
Internal use only
Is the criteria type selectable?
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= |
|
#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= |
|
Queryable
- Included
Criteria::Queryable::Optional
- Included
Criteria::Queryable::Aggregable
- Included
#aggregating Flag for whether or not we are aggregating., #aggregating=, | |
#aggregating? | Has the aggregable enter an aggregation state. |
#pipeline, #pipeline The aggregation pipeline. |
Criteria::Queryable::Mergeable
- Included
Instance Method Summary
-
#==(other) ⇒ true | false
Returns true if the supplied
Enumerable
orCriteria
is equal to the results of thisCriteria
or the criteria itself. - #_enumerable_find Internal use only Internal use only
- #_findable_find Internal use only Internal use only
-
#as_json(options = nil) ⇒ String
Needed to properly get a criteria back as json.
-
#extract_id ⇒ Object
Extract a single id from the provided criteria.
-
#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. -
#field_list ⇒ Array<String>
Get the list of included fields.
-
#find(*args) {|Object| ... } ⇒ Document | Array<Document> | nil
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.
- #for_js(javascript, scope = {}) ⇒ Criteria deprecated Deprecated.
-
#freeze ⇒ Criteria
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.
-
#merge(other) ⇒ Criteria
Merges another object with this
Criteria
and returns a new criteria. -
#merge!(other) ⇒ Criteria
Merge the other criteria into this one.
-
#none ⇒ Criteria
Returns a criteria that will always contain zero results and never hits the database.
-
#only(*args) ⇒ Criteria
Overriden to include _type in the fields.
-
#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.
-
#read(value = nil) ⇒ Criteria
::Set
the read preference for the criteria. -
#respond_to?(name, include_private = false) ⇒ true | false
Returns true if criteria responds to the given method.
- #to_ary
- #to_criteria ⇒ Criteria deprecated Deprecated.
-
#to_proc ⇒ Proc
Convert the criteria to a proc.
-
#type(types) ⇒ Criteria
Adds a criterion to the
Criteria
that specifies a type or an::Array
of types that must be matched. -
#where(*args) ⇒ Criteria
This is the general entry point for most MongoDB queries.
-
#without(*args) ⇒ Criteria
Overriden to exclude _id from the fields.
-
#without_options ⇒ Criteria
Get a version of this criteria without the options.
-
#check_for_missing_documents!(result, ids)
private
Internal use only
Internal use only
Are documents in the query missing, and are we configured to raise an error?
-
#initialize_copy(other) ⇒ nil
private
Internal use only
Internal use only
Clone or dup the current
Criteria
. -
#merge_type_selection ⇒ true | false
private
For models where inheritance is at play we need to add the type selection.
-
#method_missing ⇒ Object
private
Used for chaining
Criteria
scopes together in the for of class methods on theDocument
the criteria is for. -
#selector_with_type_selection ⇒ Hash
private
Internal use only
Internal use only
Get a new selector with type selection in it.
-
#type_selection ⇒ Hash
private
Internal use only
Internal use only
Get the selector for type selection.
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 |
#find_or_create_by! | Find the first |
#find_or_initialize_by | Find the first |
#first_or_create | Find the first |
#first_or_create! | Find the first |
#first_or_initialize | Find the first |
#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 |
#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 | Alias for Queryable::Optional#ascending. |
#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 |
|
#comment | Associate a comment with the query. |
#cursor_type |
|
#desc | Alias for Queryable::Optional#descending. |
#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 | Alias for Queryable::Optional#skip. |
#only | Limits the results to only contain the fields provided. |
#order | Alias for Queryable::Optional#order_by. |
#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 |
#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.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing ⇒ Object
(private)
Used for chaining Criteria
scopes together in the for of class methods on the Document
the criteria is for.
# 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.
Instance Attribute Details
#_raw_results ⇒ nil
| Hash (rw)
An internal helper for getting/setting the “raw” flag on a given criteria object.
# File 'lib/mongoid/criteria.rb', line 215
attr_accessor :_raw_results
#association (rw)
[ GitHub ]# File 'lib/mongoid/criteria.rb', line 68
attr_accessor :, :klass, :parent_document, :association
#documents ⇒ Array<Document> (rw)
Get the documents from the embedded criteria.
# File 'lib/mongoid/criteria.rb', line 150
def documents @documents ||= [] end
#documents=(docs) ⇒ Array<Document> (rw)
::Set
the embedded documents on the criteria.
# 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 :, :klass, :parent_document, :association
#embedded? ⇒ true
| false
(rw)
Is the criteria for embedded documents?
# File 'lib/mongoid/criteria.rb', line 171
def !!@embedded end
#empty_and_chainable? ⇒ true
| false
(readonly)
Is the criteria an empty but chainable criteria?
# 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 :, :klass, :parent_document, :association
#parent_document (rw)
[ GitHub ]# File 'lib/mongoid/criteria.rb', line 68
attr_accessor :, :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.)
# File 'lib/mongoid/criteria.rb', line 221
def raw_results? _raw_results && _raw_results[:raw] end
#type_selectable? ⇒ true
| false
(readonly, private)
Is the criteria type selectable?
# 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.
# File 'lib/mongoid/criteria.rb', line 232
def typecast_results? _raw_results && _raw_results[:typed] end
Instance Method Details
#==(other) ⇒ true
| false
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.
# File 'lib/mongoid/criteria.rb', line 78
def ==(other) return super if other.respond_to?(:selector) entries == other end
#_enumerable_find
# File 'lib/mongoid/criteria.rb', line 26
alias :_enumerable_find :find
#_findable_find
# 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
# File 'lib/mongoid/criteria.rb', line 140
def as_json( = nil) entries.as_json( ) end
#check_for_missing_documents!(result, ids) (private)
Are documents in the query missing, and are we configured to raise an error?
# 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_id ⇒ Object
Extract a single id from the provided criteria. Could be in an $and query or a straight _id query.
# 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)
# File 'lib/mongoid/criteria.rb', line 256
def extras(extras) crit = clone crit. .merge!(extras) crit end
#field_list ⇒ Array<String>
Get the list of included fields.
# File 'lib/mongoid/criteria.rb', line 268
def field_list if [:fields] [:fields].keys.reject{ |key| key == klass.discriminator_key } else [] end end
#find(*args) {|Object| ... } ⇒ Document | Array<Document> | nil
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.
# 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
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.
#freeze ⇒ Criteria
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.
# File 'lib/mongoid/criteria.rb', line 284
def freeze context and inclusions and super end
#initialize_copy(other) ⇒ nil
(private)
Clone or dup the current Criteria
. This will return a new criteria with the selector, options, klass, embedded options, etc intact.
# File 'lib/mongoid/criteria.rb', line 574
def initialize_copy(other) @inclusions = other.inclusions.dup @scoping_options = other. @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.
# 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.
# 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) .merge!(other. ) self.documents = other.documents.dup unless other.documents.empty? self. = other. self.inclusions = (inclusions + other.inclusions).uniq self._raw_results = self._raw_results || other._raw_results self end
#merge_type_selection ⇒ true
| false
(private)
For models where inheritance is at play we need to add the type selection.
# File 'lib/mongoid/criteria.rb', line 612
def merge_type_selection selector.merge!(type_selection) if type_selectable? end
#none ⇒ Criteria
Returns a criteria that will always contain zero results and never hits the database.
# File 'lib/mongoid/criteria.rb', line 353
def none @none = true and self end
#only(*args) ⇒ Criteria
Overriden to include _type in the fields.
#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.
# 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.
# File 'lib/mongoid/criteria.rb', line 395
def read(value = nil) clone.tap do |criteria| criteria. .merge!(read: value) end end
#respond_to?(name, include_private = false) ⇒ true
| false
Returns true if criteria responds to the given method.
#selector_with_type_selection ⇒ Hash (private)
Get a new selector with type selection in it.
# 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_criteria ⇒ Criteria
Convenience for objects that want to be merged into a criteria.
# File 'lib/mongoid/criteria.rb', line 436
def to_criteria self end
#to_proc ⇒ Proc
Convert the criteria to a proc.
# 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.
# File 'lib/mongoid/criteria.rb', line 461
def type(types) any_in(self.discriminator_key.to_sym => Array(types)) end
#type_selection ⇒ Hash (private)
Get the selector for type selection.
#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.
# 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) && raise Errors::UnsupportedJavascript.new(klass, expression) end end super end
#without(*args) ⇒ Criteria
Overriden to exclude _id from the fields.
# File 'lib/mongoid/criteria.rb', line 409
def without(*args) args -= id_fields super(*args) end
#without_options ⇒ Criteria
Get a version of this criteria without the options.
# File 'lib/mongoid/criteria.rb', line 508
def crit = clone crit. .clear crit end