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.
Example setup:
criteria = Criteria.new
criteria.select(:field => "value").only(:field).skip(20).limit(20)
criteria.execute
Constant Summary collapse
- AGGREGATE_REDUCE =
"function(obj, prev) { prev.count++; }"
- GROUP_REDUCE =
"function(obj, prev) { prev.group.push(obj); }"
Instance Attribute Summary collapse
-
#klass ⇒ Object
Returns the value of attribute klass.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
-
#selector ⇒ Object
readonly
Returns the value of attribute selector.
-
#type ⇒ Object
readonly
Returns the value of attribute type.
Class Method Summary collapse
-
.translate(*args) ⇒ Object
Translate the supplied arguments into a
Criteria
object.
Instance Method Summary collapse
-
#aggregate(klass = nil) ⇒ Object
Aggregate the criteria.
-
#all(selections = {}) ⇒ Object
Adds a criterion to the
Criteria
that specifies values that must all be matched in order to return results. -
#count(klass = nil) ⇒ Object
Get the count of matching documents in the database for the
Criteria
. -
#excludes(exclusions = {}) ⇒ Object
Adds a criterion to the
Criteria
that specifies values that are not allowed to match any document in the database. -
#execute(klass = nil) ⇒ Object
Execute the criteria.
-
#extras(extras) ⇒ Object
Adds a criterion to the
Criteria
that specifies additional options to be passed to the Ruby driver, in the exact format for the driver. -
#group(klass = nil) ⇒ Object
Groups the criteria.
-
#id(object_id) ⇒ Object
Adds a criterion to the
Criteria
that specifies an id that must be matched. -
#in(inclusions = {}) ⇒ Object
Adds a criterion to the
Criteria
that specifies values where any can be matched in order to return results. -
#initialize(type, klass = nil) ⇒ Criteria
constructor
Create the new
Criteria
object. -
#limit(value = 20) ⇒ Object
Adds a criterion to the
Criteria
that specifies the maximum number of results to return. -
#not_in(exclusions) ⇒ Object
Adds a criterion to the
Criteria
that specifies values where none should match in order to return results. -
#offset ⇒ Object
Returns the offset option.
-
#order_by(params = []) ⇒ Object
Adds a criterion to the
Criteria
that specifies the sort order of the returned documents in the database. -
#page ⇒ Object
Either returns the page option and removes it from the options, or returns a default value of 1.
-
#select(*args) ⇒ Object
Adds a criterion to the
Criteria
that specifies the fields that will get returned from the Document. -
#skip(value = 0) ⇒ Object
Adds a criterion to the
Criteria
that specifies how many results to skip when returning Documents. -
#where(selector = {}) ⇒ Object
Adds a criterion to the
Criteria
that specifies values that must be matched in order to return results.
Constructor Details
#initialize(type, klass = nil) ⇒ Criteria
Create the new Criteria
object. This will initialize the selector and options hashes, as well as the type of criteria.
Options:
type: One of :all, :first:, or :last klass: The class to execute on.
186 187 188 |
# File 'lib/mongoid/criteria.rb', line 186 def initialize(type, klass = nil) @selector, @options, @type, @klass = {}, {}, type, klass end |
Instance Attribute Details
#klass ⇒ Object
Returns the value of attribute klass.
17 18 19 |
# File 'lib/mongoid/criteria.rb', line 17 def klass @klass end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
18 19 20 |
# File 'lib/mongoid/criteria.rb', line 18 def @options end |
#selector ⇒ Object (readonly)
Returns the value of attribute selector.
18 19 20 |
# File 'lib/mongoid/criteria.rb', line 18 def selector @selector end |
#type ⇒ Object (readonly)
Returns the value of attribute type.
18 19 20 |
# File 'lib/mongoid/criteria.rb', line 18 def type @type end |
Class Method Details
.translate(*args) ⇒ Object
Translate the supplied arguments into a Criteria
object.
If the passed in args is a single String
, then it will construct an id Criteria
from it.
If the passed in args are a type and a hash, then it will construct the Criteria
with the proper selector, options, and type.
Options:
args: either a String
or a Symbol
, +Hash combination.
Example:
Criteria.translate("4ab2bc4b8ad548971900005c")
Criteria.translate(:all, :conditions => { :field => "value"}, :limit => 20)
Returns a new Criteria
object.
311 312 313 314 315 |
# File 'lib/mongoid/criteria.rb', line 311 def self.translate(*args) type, params = args[0], args[1] || {} return new(:first).id(type.to_s) if type.is_a?(String) return new(type).where(params.delete(:conditions)).extras(params) end |
Instance Method Details
#aggregate(klass = nil) ⇒ Object
Aggregate the criteria. This will take the internally built selector and options and pass them on to the Ruby driver’s group() method on the collection. The collection itself will be retrieved from the class provided, and once the query has returned it will provided a grouping of keys with counts.
Example:
criteria.select(:field1).where(:field1 => "Title").aggregate(Person)
29 30 31 32 |
# File 'lib/mongoid/criteria.rb', line 29 def aggregate(klass = nil) @klass = klass if klass @klass.collection.group(@options[:fields], @selector, { :count => 0 }, AGGREGATE_REDUCE) end |
#all(selections = {}) ⇒ Object
Adds a criterion to the Criteria
that specifies values that must all be matched in order to return results. Similar to an “in” clause but the underlying conditional logic is an “AND” and not an “OR”. The MongoDB conditional operator that will be used is “$all”.
Options:
selections: A Hash
where the key is the field name and the value is an Array
of values that must all match.
Example:
criteria.all(:field => ["value1", "value2"])
criteria.all(:field1 => ["value1", "value2"], :field2 => ["value1"])
Returns: self
51 52 53 |
# File 'lib/mongoid/criteria.rb', line 51 def all(selections = {}) selections.each { |key, value| @selector[key] = { "$all" => value } }; self end |
#count(klass = nil) ⇒ Object
Get the count of matching documents in the database for the Criteria
.
Options:
klass: Optional class that the collection will be retrieved from.
Example:
criteria.count
Returns: Integer
66 67 68 69 |
# File 'lib/mongoid/criteria.rb', line 66 def count(klass = nil) @klass = klass if klass return @klass.collection.find(@selector, @options).count end |
#excludes(exclusions = {}) ⇒ Object
Adds a criterion to the Criteria
that specifies values that are not allowed to match any document in the database. The MongoDB conditional operator that will be used is “$ne”.
Options:
excludes: A Hash
where the key is the field name and the value is a value that must not be equal to the corresponding field value in the database.
Example:
criteria.excludes(:field => "value1")
criteria.excludes(:field1 => "value1", :field2 => "value1")
Returns: self
87 88 89 |
# File 'lib/mongoid/criteria.rb', line 87 def excludes(exclusions = {}) exclusions.each { |key, value| @selector[key] = { "$ne" => value } }; self end |
#execute(klass = nil) ⇒ Object
Execute the criteria. This will take the internally built selector and options and pass them on to the Ruby driver’s find() method on the collection. The collection itself will be retrieved from the class provided, and once the query has returned new documents of the type of class provided will be instantiated.
If this is a Criteria
to only find the first object, this will return a single object of the type of class provided.
If this is a Criteria
to find multiple results, will return an Array
of objects of the type of class provided.
101 102 103 104 105 |
# File 'lib/mongoid/criteria.rb', line 101 def execute(klass = nil) @klass = klass if klass return @klass.new(klass.collection.find_one(@selector, @options)) if type == :first return @klass.collection.find(@selector, @options).collect { |doc| @klass.new(doc) } end |
#extras(extras) ⇒ Object
Adds a criterion to the Criteria
that specifies additional options to be passed to the Ruby driver, in the exact format for the driver.
Options:
extras: A Hash
that gets set to the driver options.
Example:
criteria.extras(:limit => 20, :skip => 40)
Returns: self
119 120 121 |
# File 'lib/mongoid/criteria.rb', line 119 def extras(extras) @options = extras; self end |
#group(klass = nil) ⇒ Object
Groups the criteria. This will take the internally built selector and options and pass them on to the Ruby driver’s group() method on the collection. The collection itself will be retrieved from the class provided, and once the query has returned it will provided a grouping of keys with objects.
Example:
criteria.select(:field1).where(:field1 => "Title").group(Person)
132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/mongoid/criteria.rb', line 132 def group(klass = nil) @klass = klass if klass @klass.collection.group( @options[:fields], @selector, { :group => [] }, GROUP_REDUCE ).collect do |docs| docs["group"] = docs["group"].collect { |attrs| @klass.new(attrs) }; docs end end |
#id(object_id) ⇒ Object
Adds a criterion to the Criteria
that specifies an id that must be matched.
Options:
object_id: A String
representation of a Mongo::ObjectID
Example:
criteria.id("4ab2bc4b8ad548971900005c")
Returns: self
175 176 177 |
# File 'lib/mongoid/criteria.rb', line 175 def id(object_id) @selector[:_id] = Mongo::ObjectID.from_string(object_id); self end |
#in(inclusions = {}) ⇒ Object
Adds a criterion to the Criteria
that specifies values where any can be matched in order to return results. This is similar to an SQL “IN” clause. The MongoDB conditional operator that will be used is “$in”.
Options:
inclusions: A Hash
where the key is the field name and the value is an Array
of values that any can match.
Example:
criteria.in(:field => ["value1", "value2"])
criteria.in(:field1 => ["value1", "value2"], :field2 => ["value1"])
Returns: self
160 161 162 |
# File 'lib/mongoid/criteria.rb', line 160 def in(inclusions = {}) inclusions.each { |key, value| @selector[key] = { "$in" => value } }; self end |
#limit(value = 20) ⇒ Object
Adds a criterion to the Criteria
that specifies the maximum number of results to return. This is mostly used in conjunction with skip()
to handle paginated results.
Options:
value: An Integer
specifying the max number of results. Defaults to 20.
Example:
criteria.limit(100)
Returns: self
203 204 205 |
# File 'lib/mongoid/criteria.rb', line 203 def limit(value = 20) @options[:limit] = value; self end |
#not_in(exclusions) ⇒ Object
Adds a criterion to the Criteria
that specifies values where none should match in order to return results. This is similar to an SQL “NOT IN” clause. The MongoDB conditional operator that will be used is “$nin”.
Options:
exclusions: A Hash
where the key is the field name and the value is an Array
of values that none can match.
Example:
criteria.not_in(:field => ["value1", "value2"])
criteria.not_in(:field1 => ["value1", "value2"], :field2 => ["value1"])
Returns: self
223 224 225 |
# File 'lib/mongoid/criteria.rb', line 223 def not_in(exclusions) exclusions.each { |key, value| @selector[key] = { "$nin" => value } }; self end |
#offset ⇒ Object
Returns the offset option. If a per_page option is in the list then it will replace it with a skip parameter and return the same value. Defaults to 20 if nothing was provided.
230 231 232 233 |
# File 'lib/mongoid/criteria.rb', line 230 def offset offset = @options.delete(:per_page) || 20 @options[:skip] ||= offset end |
#order_by(params = []) ⇒ Object
Adds a criterion to the Criteria
that specifies the sort order of the returned documents in the database. Similar to a SQL “ORDER BY”.
Options:
params: An Array
of [field, direction] sorting pairs.
Example:
criteria.order_by([[:field1, :asc], [:field2, :desc]])
Returns: self
247 248 249 |
# File 'lib/mongoid/criteria.rb', line 247 def order_by(params = []) @options[:sort] = params; self end |
#page ⇒ Object
Either returns the page option and removes it from the options, or returns a default value of 1.
253 254 255 |
# File 'lib/mongoid/criteria.rb', line 253 def page @options.delete(:page) || 1 end |
#select(*args) ⇒ Object
Adds a criterion to the Criteria
that specifies the fields that will get returned from the Document. Used mainly for list views that do not require all fields to be present. This is similar to SQL “SELECT” values.
Options:
args: A list of field names to retrict the returned fields to.
Example:
criteria.select(:field1, :field2, :field3)
Returns: self
270 271 272 |
# File 'lib/mongoid/criteria.rb', line 270 def select(*args) @options[:fields] = args.flatten if args.any?; self end |
#skip(value = 0) ⇒ Object
Adds a criterion to the Criteria
that specifies how many results to skip when returning Documents. This is mostly used in conjunction with limit()
to handle paginated results, and is similar to the traditional “offset” parameter.
Options:
value: An Integer
specifying the number of results to skip. Defaults to 0.
Example:
criteria.skip(20)
Returns: self
288 289 290 |
# File 'lib/mongoid/criteria.rb', line 288 def skip(value = 0) @options[:skip] = value; self end |
#where(selector = {}) ⇒ Object
Adds a criterion to the Criteria
that specifies values that must be matched in order to return results. This is similar to a SQL “WHERE” clause. This is the actual selector that will be provided to MongoDB, similar to the Javascript object that is used when performing a find() in the MongoDB console.
Options:
selectior: A Hash
that must match the attributes of the Document
.
Example:
criteria.where(:field1 => "value1", :field2 => 15)
Returns: self
332 333 334 |
# File 'lib/mongoid/criteria.rb', line 332 def where(selector = {}) @selector = selector; self end |