Class: Mongoid::Criteria
- Inherits:
-
Object
- Object
- Mongoid::Criteria
- Includes:
- Enumerable, Contextual, Mongoid::Criterion::Findable, Mongoid::Criterion::Inspection, Mongoid::Criterion::Marshalable, Mongoid::Criterion::Modifiable, Mongoid::Criterion::Scoping, Origin::Queryable
- Defined in:
- lib/mongoid/criteria.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 collapse
- CHECK =
Static array used to check with method missing - we only need to ever instantiate once.
[]
Instance Attribute Summary collapse
-
#embedded ⇒ Object
Returns the value of attribute embedded.
-
#klass ⇒ Object
Returns the value of attribute klass.
Instance Method Summary collapse
-
#==(other) ⇒ true, false
Returns true if the supplied
Enumerable
orCriteria
is equal to the results of thisCriteria
or the criteria itself. -
#as_json(options = nil) ⇒ String
Needed to properly get a criteria back as json.
-
#cache ⇒ Criteria
Tells the criteria that the cursor that gets returned needs to be cached.
-
#cached? ⇒ true, false
Will return true if the cache option has been set.
-
#documents ⇒ Array<Document>
Get the documents from the embedded criteria.
-
#documents=(docs) ⇒ Array<Document>
Set the embedded documents on the criteria.
-
#embedded? ⇒ true, false
Is the criteria for embedded documents?.
-
#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.
-
#for_js(javascript, scope = {}) ⇒ Criteria
Find documents by the provided javascript and scope.
-
#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.
-
#includes(*relations) ⇒ Criteria
Eager loads all the provided relations.
-
#inclusions ⇒ Array<Metadata>
Get a list of criteria that are to be executed for eager loading.
-
#inclusions=(value) ⇒ Array<Metadata>
Set the inclusions for the criteria.
-
#initialize(klass) ⇒ Criteria
constructor
Initialize the new criteria.
-
#merge(other) ⇒ Criteria
criteria.merge({ klass: Band, where: { name: “Depeche Mode” }, order_by: { name: 1 } }).
-
#merge!(other) ⇒ Criteria
Merge the other criteria into this one.
-
#only(*args) ⇒ Criteria
Overriden to include _type in the fields.
-
#respond_to?(name, include_private = false) ⇒ true, false
Returns true if criteria responds to the given method.
-
#to_criteria ⇒ Criteria
Convenience for objects that want to be merged into a criteria.
-
#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(expression) ⇒ Criteria
This is the general entry point for most MongoDB queries.
-
#with(options) ⇒ Criteria
Tell the next persistance operation to query from a specific collection, database or session.
-
#without_options ⇒ Criteria
Get a version of this criteria without the options.
Methods included from Mongoid::Criterion::Scoping
#apply_default_scope, #remove_scoping, #scoped, #scoped?, #scoping_options, #scoping_options=, #unscoped, #unscoped?, #with_default_scope
Methods included from Mongoid::Criterion::Modifiable
#build, #create, #create!, #find_or_create_by, #find_or_initialize_by, #first_or_create, #first_or_create!, #first_or_initialize
Methods included from Mongoid::Criterion::Marshalable
Methods included from Mongoid::Criterion::Findable
#execute_or_raise, #find, #for_ids, #from_map_or_db, #multiple_from_map_or_db
Methods included from Mongoid::Criterion::Inspection
Methods included from Contextual
Constructor Details
#initialize(klass) ⇒ Criteria
Initialize the new criteria.
191 192 193 194 |
# File 'lib/mongoid/criteria.rb', line 191 def initialize(klass) @klass = klass klass ? super(klass.aliased_fields, klass.fields) : super({}, {}) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object (private)
Used for chaining Criteria
scopes together in the for of class methods on the Document
the criteria is for.
510 511 512 513 514 515 516 517 518 519 520 |
# File 'lib/mongoid/criteria.rb', line 510 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 |
Instance Attribute Details
#embedded ⇒ Object
Returns the value of attribute embedded.
32 33 34 |
# File 'lib/mongoid/criteria.rb', line 32 def @embedded end |
#klass ⇒ Object
Returns the value of attribute klass.
32 33 34 |
# File 'lib/mongoid/criteria.rb', line 32 def klass @klass 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.
44 45 46 47 |
# File 'lib/mongoid/criteria.rb', line 44 def ==(other) return super if other.respond_to?(:selector) entries == other end |
#as_json(options = nil) ⇒ String
Needed to properly get a criteria back as json
57 58 59 |
# File 'lib/mongoid/criteria.rb', line 57 def as_json( = nil) entries.as_json() end |
#cache ⇒ Criteria
Tells the criteria that the cursor that gets returned needs to be cached. This is so multiple iterations don’t hit the database multiple times, however this is not advisable when working with large data sets as the entire results will get stored in memory.
70 71 72 73 74 |
# File 'lib/mongoid/criteria.rb', line 70 def cache crit = clone crit..merge!(cache: true) crit end |
#cached? ⇒ true, false
Will return true if the cache option has been set.
82 83 84 |
# File 'lib/mongoid/criteria.rb', line 82 def cached? [:cache] == true end |
#documents ⇒ Array<Document>
Get the documents from the embedded criteria.
94 95 96 |
# File 'lib/mongoid/criteria.rb', line 94 def documents @documents ||= [] end |
#documents=(docs) ⇒ Array<Document>
Set the embedded documents on the criteria.
107 108 109 |
# File 'lib/mongoid/criteria.rb', line 107 def documents=(docs) @documents = docs end |
#embedded? ⇒ true, false
Is the criteria for embedded documents?
119 120 121 |
# File 'lib/mongoid/criteria.rb', line 119 def !!@embedded end |
#extract_id ⇒ Object
Extract a single id from the provided criteria. Could be in an $and query or a straight _id query.
132 133 134 |
# File 'lib/mongoid/criteria.rb', line 132 def extract_id selector.extract_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)
147 148 149 150 151 |
# File 'lib/mongoid/criteria.rb', line 147 def extras(extras) crit = clone crit..merge!(extras) crit end |
#field_list ⇒ Array<String>
Get the list of included fields.
161 162 163 164 165 166 167 |
# File 'lib/mongoid/criteria.rb', line 161 def field_list if [:fields] [:fields].keys.reject{ |key| key == "_type" } else [] end end |
#for_js(javascript, scope = {}) ⇒ Criteria
Find documents by the provided javascript and scope. Uses a $where but is different from Criteria#where in that it will pass a code object to the query instead of a pure string. Safe against Javascript injection attacks.
447 448 449 |
# File 'lib/mongoid/criteria.rb', line 447 def for_js(javascript, scope = {}) js_query(Moped::BSON::Code.new(javascript, scope)) end |
#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.
179 180 181 |
# File 'lib/mongoid/criteria.rb', line 179 def freeze context and inclusions and super end |
#includes(*relations) ⇒ Criteria
This will only work if Mongoid’s identity map is enabled. To do so set identity_map_enabled: true in your mongoid.yml
This will work for embedded relations that reference another collection via belongs_to as well.
Eager loading brings all the documents into memory, so there is a sweet spot on the performance gains. Internal benchmarks show that eager loading becomes slower around 100k documents, but this will naturally depend on the specific application.
Eager loads all the provided relations. Will load all the documents into the identity map who’s ids match based on the extra query for the ids.
220 221 222 223 224 225 226 227 |
# File 'lib/mongoid/criteria.rb', line 220 def includes(*relations) relations.flatten.each do |name| = klass.reflect_on_association(name) raise Errors::InvalidIncludes.new(klass, relations) unless inclusions.push() unless inclusions.include?() end clone end |
#inclusions ⇒ Array<Metadata>
Get a list of criteria that are to be executed for eager loading.
237 238 239 |
# File 'lib/mongoid/criteria.rb', line 237 def inclusions @inclusions ||= [] end |
#inclusions=(value) ⇒ Array<Metadata>
Set the inclusions for the criteria.
251 252 253 |
# File 'lib/mongoid/criteria.rb', line 251 def inclusions=(value) @inclusions = value end |
#merge(other) ⇒ Criteria
criteria.merge({
klass: Band,
where: { name: "Depeche Mode" },
order_by: { name: 1 }
})
275 276 277 278 279 |
# File 'lib/mongoid/criteria.rb', line 275 def merge(other) crit = clone crit.merge!(other) crit end |
#merge!(other) ⇒ Criteria
Merge the other criteria into this one.
291 292 293 294 295 296 297 298 299 |
# File 'lib/mongoid/criteria.rb', line 291 def merge!(other) criteria = other.to_criteria selector.merge!(criteria.selector) .merge!(criteria.) self.documents = criteria.documents.dup unless criteria.documents.empty? self. = criteria. self.inclusions = (inclusions + criteria.inclusions.dup).uniq self end |
#only(*args) ⇒ Criteria
Overriden to include _type in the fields.
311 312 313 314 315 316 317 318 319 |
# File 'lib/mongoid/criteria.rb', line 311 def only(*args) return clone if args.flatten.empty? args = args.flatten if klass.hereditary? super(*args.push(:_type)) else super(*args) end end |
#respond_to?(name, include_private = false) ⇒ true, false
Returns true if criteria responds to the given method.
330 331 332 |
# File 'lib/mongoid/criteria.rb', line 330 def respond_to?(name, include_private = false) super || klass.respond_to?(name) || CHECK.respond_to?(name, include_private) end |
#to_criteria ⇒ Criteria
Convenience for objects that want to be merged into a criteria.
344 345 346 |
# File 'lib/mongoid/criteria.rb', line 344 def to_criteria self end |
#to_proc ⇒ Proc
Convert the criteria to a proc.
356 357 358 |
# File 'lib/mongoid/criteria.rb', line 356 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.
370 371 372 |
# File 'lib/mongoid/criteria.rb', line 370 def type(types) any_in(_type: Array(types)) end |
#where(expression) ⇒ 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.
392 393 394 395 396 397 |
# File 'lib/mongoid/criteria.rb', line 392 def where(expression) if expression.is_a?(::String) && raise Errors::UnsupportedJavascript.new(klass, expression) end super end |
#with(options) ⇒ Criteria
Tell the next persistance operation to query from a specific collection, database or session.
414 415 416 417 |
# File 'lib/mongoid/criteria.rb', line 414 def with() Threaded.(klass, ) self end |
#without_options ⇒ Criteria
Get a version of this criteria without the options.
427 428 429 430 431 |
# File 'lib/mongoid/criteria.rb', line 427 def crit = clone crit..clear crit end |