Class: Mongoid::Criteria

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Mongoid::Clients::Options, Mongoid::Clients::Sessions, Contextual, Findable, Includable, Inspectable, Marshalable, Modifiable, Options, Queryable, Scopable
Defined in:
build/mongoid-7.0/lib/mongoid/criteria.rb,
build/mongoid-7.0/lib/mongoid/criteria/options.rb,
build/mongoid-7.0/lib/mongoid/criteria/findable.rb,
build/mongoid-7.0/lib/mongoid/criteria/scopable.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable.rb,
build/mongoid-7.0/lib/mongoid/criteria/includable.rb,
build/mongoid-7.0/lib/mongoid/criteria/modifiable.rb,
build/mongoid-7.0/lib/mongoid/criteria/permission.rb,
build/mongoid-7.0/lib/mongoid/criteria/inspectable.rb,
build/mongoid-7.0/lib/mongoid/criteria/marshalable.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/key.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/smash.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/options.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/optional.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/pipeline.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/selector.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/macroable.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/mergeable.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/aggregable.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/selectable.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/forwardable.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/set.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/date.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/hash.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/time.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/array.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/range.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/object.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/regexp.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/string.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/symbol.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/boolean.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/numeric.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/date_time.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/nil_class.rb,
build/mongoid-7.0/lib/mongoid/criteria/queryable/extensions/big_decimal.rb,
build/mongoid-7.0/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.

Defined Under Namespace

Modules: Findable, Includable, Inspectable, Marshalable, Modifiable, Options, Permission, Queryable, Scopable

Constant Summary collapse

CHECK =

Static array used to check with method missing - we only need to ever instantiate once.

Since:

  • 4.0.0

[]

Instance Attribute Summary collapse

Attributes included from Modifiable

#create_attrs, #create_attrs Additional attributes to add to the Document upon creation.

Attributes included from Queryable

#aliases, #aliases The aliases., #driver, #driver The Mongo driver being used., #serializers, #serializers The serializers.

Attributes included from Queryable::Optional

#options, #options The query options.

Attributes included from Queryable::Aggregable

#aggregating, #aggregating Flag for whether or not we are aggregating., #pipeline, #pipeline The aggregation pipeline.

Attributes included from Queryable::Mergeable

#strategy, #strategy The name of the current strategy.

Instance Method Summary collapse

Methods included from Mongoid::Clients::Sessions

#with_session

Methods included from Mongoid::Clients::Options

#collection, #collection_name, #mongo_client, #persistence_context, #with

Methods included from Scopable

#apply_default_scope, #remove_scoping, #scoped, #scoped?, #scoping_options, #scoping_options=, #unscoped, #unscoped?, #with_default_scope

Methods included from Modifiable

#build, #create, #create!, #create_with, #find_or_create_by, #find_or_create_by!, #find_or_initialize_by, #first_or_create, #first_or_create!, #first_or_initialize

Methods included from Marshalable

#marshal_dump, #marshal_load

Methods included from Includable

#includes, #inclusions, #inclusions=

Methods included from Inspectable

#inspect

Methods included from Findable

#execute_or_raise, #find, #for_ids, #multiple_from_db

Methods included from Queryable::Optional

#ascending, #batch_size, #collation, #comment, #cursor_type, #descending, forwardables, #hint, #limit, #max_scan, #max_time_ms, #no_timeout, #order_by, #reorder, #skip, #slice, #snapshot

Methods included from Queryable::Macroable

#key

Methods included from Selectable

#atomic_selector

Methods included from Queryable::Aggregable

#aggregating?, #group, #project, #unwind

Methods included from Queryable::Mergeable

#intersect, #override, #reset_strategies!, #union

Methods included from Contextual

#context

Constructor Details

#initialize(klass) ⇒ Criteria

Initialize the new criteria.

Examples:

Init the new criteria.

Criteria.new(Band)

Parameters:

  • klass (Class)

    The model class.

Since:

  • 1.0.0



198
199
200
201
202
203
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 198

def initialize(klass)
  @klass = klass
  @embedded = nil
  @none = nil
  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.

Examples:

Handle method missing.

criteria.method_missing(:name)

Parameters:

  • name (Symbol)

    The method name.

  • args (Array)

    The arguments.

Returns:

  • (Object)

    The result of the method call.

Since:

  • 1.0.0



506
507
508
509
510
511
512
513
514
515
516
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 506

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

#associationObject

Returns the value of attribute association.



39
40
41
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 39

def association
  @association
end

#embeddedObject

Returns the value of attribute embedded.



39
40
41
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 39

def embedded
  @embedded
end

#klassObject

Returns the value of attribute klass.



39
40
41
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 39

def klass
  @klass
end

#parent_documentObject

Returns the value of attribute parent_document.



39
40
41
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 39

def parent_document
  @parent_document
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.

Since:

  • 1.0.0



51
52
53
54
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 51

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

Examples:

Get the criteria as json.

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

Parameters:

  • options (Hash) (defaults to: nil)

    Options to pass through to the serializer.

Returns:

  • (String)

    The JSON string.



64
65
66
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 64

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

#cacheCriteria

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.

Examples:

Flag the criteria as cached.

criteria.cache

Returns:



77
78
79
80
81
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 77

def cache
  crit = clone
  crit.options.merge!(cache: true)
  crit
end

#cached?true, false

Will return true if the cache option has been set.

Examples:

Is the criteria cached?

criteria.cached?

Returns:

  • (true, false)

    If the criteria is flagged as cached.



89
90
91
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 89

def cached?
  options[:cache] == true
end

#documentsArray<Document>

Get the documents from the embedded criteria.

Examples:

Get the documents.

criteria.documents

Returns:

Since:

  • 3.0.0



101
102
103
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 101

def documents
  @documents ||= []
end

#documents=(docs) ⇒ Array<Document>

Set the embedded documents on the criteria.

Examples:

Set the documents.

Parameters:

  • docs (Array<Document>)

    The embedded documents.

Returns:

  • (Array<Document>)

    The embedded documents.

Since:

  • 3.0.0



114
115
116
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 114

def documents=(docs)
  @documents = docs
end

#embedded?true, false

Is the criteria for embedded documents?

Examples:

Is the criteria for embedded documents?

criteria.embedded?

Returns:

  • (true, false)

    If the criteria is embedded.

Since:

  • 3.0.0



126
127
128
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 126

def embedded?
  !!@embedded
end

#empty_and_chainable?true, false

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.

Since:

  • 4.0.0



272
273
274
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 272

def empty_and_chainable?
  !!@none
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.

Since:

  • 2.3.0



139
140
141
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 139

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)

Examples:

Add extra params to the criteria.

Parameters:

  • extras (Hash)

    The extra driver options.

Returns:

Since:

  • 2.0.0



154
155
156
157
158
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 154

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:

  • (Array<String>)

    The fields.

Since:

  • 2.0.0



168
169
170
171
172
173
174
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 168

def field_list
  if options[:fields]
    options[: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.

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:

Since:

  • 3.1.0



437
438
439
440
441
442
443
444
445
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 437

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:

Since:

  • 2.0.0



186
187
188
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 186

def freeze
  context and inclusions and 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.

criteri.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:



225
226
227
228
229
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 225

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)

    The criteria to merge in.

Returns:

Since:

  • 3.0.0



241
242
243
244
245
246
247
248
249
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 241

def merge!(other)
  criteria = other.to_criteria
  selector.merge!(criteria.selector)
  options.merge!(criteria.options)
  self.documents = criteria.documents.dup unless criteria.documents.empty?
  self.scoping_options = criteria.scoping_options
  self.inclusions = (inclusions + criteria.inclusions).uniq
  self
end

#noneCriteria

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

Examples:

Return a none criteria.

criteria.none

Returns:

Since:

  • 4.0.0



260
261
262
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 260

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:

  • args (Array<Symbol>)

    The names of the fields.

Returns:

Since:

  • 1.0.0



286
287
288
289
290
291
292
293
294
295
296
297
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 286

def only(*args)
  return clone if args.flatten.empty?
  args = args.flatten
  if (args & Fields::IDS).empty?
    args.unshift(:_id)
  end
  if klass.hereditary?
    super(*args.push(:_type))
  else
    super(*args)
  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:

Since:

  • 5.0.0



309
310
311
312
313
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 309

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.



339
340
341
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 339

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

#to_criteriaCriteria

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

Examples:

Convert to a criteria.

criteria.to_criteria

Returns:

Since:

  • 3.0.0



353
354
355
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 353

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.

Since:

  • 3.0.0



365
366
367
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 365

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:



379
380
381
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 379

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.

Examples:

Add a standard selection.

criteria.where(name: "syd")

Add a javascript selection.

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

Parameters:

  • expression (String, Hash)

    The javascript or standard selection.

Returns:

Raises:

  • (UnsupportedJavascript)

    If provided a string and the criteria is embedded.

Since:

  • 1.0.0



401
402
403
404
405
406
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 401

def where(expression)
  if expression.is_a?(::String) && embedded?
    raise Errors::UnsupportedJavascript.new(klass, expression)
  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 (Array<Symbol>)

    The names of the fields.

Returns:

Since:

  • 4.0.3



325
326
327
328
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 325

def without(*args)
  args -= Fields::IDS
  super(*args)
end

#without_optionsCriteria

Get a version of this criteria without the options.

Examples:

Get the criteria without options.

criteria.without_options

Returns:

Since:

  • 3.0.4



417
418
419
420
421
# File 'build/mongoid-7.0/lib/mongoid/criteria.rb', line 417

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