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.

Examples:

Create and execute a criteria.

criteria = Criteria.new
criteria.only(:field).where(:field => "value").skip(20).limit(20)
criteria.execute

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Mongoid::Criterion::Optional

#ascending, #cache, #cached?, #descending, #extras, #for_ids, #limit, #offset, #order_by, #skip, #type

Methods included from Mongoid::Criterion::Inspection

#inspect

Methods included from Mongoid::Criterion::Inclusion

#all, #all_of, #also_in, #and, #any_of, #execute_or_raise, #find, #from_map_or_db, #in, #includes, #inclusions, #load_ids, #near, #where

Methods included from Mongoid::Criterion::Exclusion

#excludes, #fields, #not_in, #only, #without

Methods included from Mongoid::Criterion::Creational

#create

Methods included from Mongoid::Criterion::Builder

#build

Constructor Details

#initialize(klass, embedded = false) ⇒ Criteria

Create the new Criteria object. This will initialize the selector and options hashes, as well as the type of criteria.

Examples:

Instantiate a new criteria.

Criteria.new(Model, true)


205
206
207
208
# File 'lib/mongoid/criteria.rb', line 205

def initialize(klass, embedded = false)
  @selector = Criterion::Selector.new(klass)
  @options, @klass, @documents, @embedded = {}, klass, [], embedded
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (protected)

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



376
377
378
379
380
381
382
383
384
# File 'lib/mongoid/criteria.rb', line 376

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

Instance Attribute Details

#documentsObject

Returns the value of attribute documents.



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

def documents
  @documents
end

#embeddedObject

Returns the value of attribute embedded.



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

def embedded
  @embedded
end

#field_listObject

Returns the value of attribute field_list.



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

def field_list
  @field_list
end

#idsObject

Returns the value of attribute ids.



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

def ids
  @ids
end

#klassObject

Returns the value of attribute klass.



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

def klass
  @klass
end

#optionsObject

Returns the value of attribute options.



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

def options
  @options
end

#selectorObject

Returns the value of attribute selector.



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

def selector
  @selector
end

Instance Method Details

#+(other) ⇒ Object

Concatinate the criteria with another enumerable. If the other is a Criteria then it needs to get the collection from it.

Examples:

Concat 2 criteria.

criteria + criteria


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

def +(other)
  entries + comparable(other)
end

#-(other) ⇒ Object

Returns the difference between the criteria and another enumerable. If the other is a Criteria then it needs to get the collection from it.

Examples:

Get the difference of 2 criteria.

criteria - criteria


87
88
89
# File 'lib/mongoid/criteria.rb', line 87

def -(other)
  entries - comparable(other)
end

#==(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.



99
100
101
102
103
104
105
106
107
108
# File 'lib/mongoid/criteria.rb', line 99

def ==(other)
  case other
  when Criteria
    self.selector == other.selector && self.options == other.options
  when Enumerable
    return (execute.entries == other)
  else
    return false
  end
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


275
276
277
# File 'lib/mongoid/criteria.rb', line 275

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

#collectionCollection

Get the collection associated with the criteria.

Examples:

Get the collection.

criteria.collection

Since:

  • 2.2.0



118
119
120
# File 'lib/mongoid/criteria.rb', line 118

def collection
  klass.collection
end

#contextMongo, Enumerable

Return or create the context in which this criteria should be executed.

This will return an Enumerable context if the class is embedded, otherwise it will return a Mongo context for root classes.

Examples:

Get the appropriate context.

criteria.context


131
132
133
# File 'lib/mongoid/criteria.rb', line 131

def context
  @context ||= Contexts.context_for(self, embedded)
end

#each(&block) ⇒ Criteria

Iterate over each Document in the results. This can take an optional block to pass to each argument in the results.

Examples:

Iterate over the criteria results.

criteria.each { |doc| p doc }


142
143
144
# File 'lib/mongoid/criteria.rb', line 142

def each(&block)
  tap { context.iterate(&block) }
end

#exists?true, false

Return true if the criteria has some Document or not.

Examples:

Are there any documents for the criteria?

criteria.exists?


152
153
154
# File 'lib/mongoid/criteria.rb', line 152

def exists?
  context.count > 0
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

Since:

  • 2.3.0



165
166
167
# File 'lib/mongoid/criteria.rb', line 165

def extract_id
  selector[:_id]
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

Since:

  • 2.0.0



179
180
181
# File 'lib/mongoid/criteria.rb', line 179

def freeze
  context and inclusions and super
end

#fuse(criteria_conditions = {}) ⇒ Criteria

Merges the supplied argument hash into a single criteria

Examples:

Fuse the criteria and the object.

criteria.fuse(:where => { :field => "value"}, :limit => 20)


191
192
193
194
195
# File 'lib/mongoid/criteria.rb', line 191

def fuse(criteria_conditions = {})
  criteria_conditions.inject(self) do |criteria, (key, value)|
    criteria.send(key, value)
  end
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 a conditions hash.

criteria.merge({ :conditions => { :title => "Sir" } })

Merge the criteria with another criteria.

criteri.merge(other_criteria)


224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/mongoid/criteria.rb', line 224

def merge(other)
  clone.tap do |crit|
    if other.is_a?(Criteria)
      crit.selector.update(other.selector)
      crit.options.update(other.options)
      crit.documents = other.documents
    else
      duped = other.dup
      crit.selector.update(duped.delete(:conditions) || {})
      crit.options.update(duped)
    end
  end
end

#raise_invalidObject

Convenience method of raising an invalid options error.

Examples:

Raise the error.

criteria.raise_invalid

Raises:

Since:

  • 2.0.0



324
325
326
# File 'lib/mongoid/criteria.rb', line 324

def raise_invalid
  raise Errors::InvalidFind.new
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)


247
248
249
250
# File 'lib/mongoid/criteria.rb', line 247

def respond_to?(name, include_private = false)
  # don't include klass private methods because method_missing won't call them
  super || @klass.respond_to?(name) || entries.respond_to?(name, include_private)
end

#scopedHash

Returns the selector and options as a Hash that would be passed to a scope for use with named scopes.

Examples:

Get the criteria as a scoped hash.

criteria.scoped


259
260
261
262
263
264
# File 'lib/mongoid/criteria.rb', line 259

def scoped
  scope_options = @options.dup
  sorting = scope_options.delete(:sort)
  scope_options[:order_by] = sorting if sorting
  { :where => @selector }.merge(scope_options)
end

#search(*args) ⇒ Array<Symbol, Criteria>

Search for documents based on a variety of args.

Examples:

Find by an id.

criteria.search(BSON::ObjectId.new)

Find by multiple ids.

criteria.search([ BSON::ObjectId.new, BSON::ObjectId.new ])

Conditionally find all matching documents.

criteria.search(:all, :conditions => { :title => "Sir" })

Conditionally find the first document.

criteria.search(:first, :conditions => { :title => "Sir" })

Conditionally find the last document.

criteria.search(:last, :conditions => { :title => "Sir" })

Since:

  • 2.0.0



303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/mongoid/criteria.rb', line 303

def search(*args)
  raise_invalid if args[0].nil?
  type = args[0]
  params = args[1] || {}
  return [ :ids, for_ids(type) ] unless type.is_a?(Symbol)
  conditions = params.delete(:conditions) || {}
  if conditions.include?(:id)
    conditions[:_id] = conditions[:id]
    conditions.delete(:id)
  end
  return [ type, where(conditions).extras(params) ]
end