Class: Mongoid::Contexts::Mongo

Inherits:
Object
  • Object
show all
Defined in:
lib/mongoid/contexts/mongo.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(criteria) ⇒ Mongo

Create the new mongo context. This will execute the queries given the selector and options against the database.

Examples:

Create a new context.

Mongoid::Contexts::Mongo.new(criteria)

Parameters:

  • criteria (Criteria)

    The criteria to create with.



245
246
247
248
249
250
251
# File 'lib/mongoid/contexts/mongo.rb', line 245

def initialize(criteria)
  @criteria = criteria
  if klass.hereditary? && !criteria.selector.keys.include?(:_type)
    @criteria = criteria.in(:_type => criteria.klass._types)
  end
  @criteria.cache if klass.cached?
end

Instance Attribute Details

#criteriaObject

Returns the value of attribute criteria.



5
6
7
# File 'lib/mongoid/contexts/mongo.rb', line 5

def criteria
  @criteria
end

Instance Method Details

#add_to_set(field, value) ⇒ Object

Perform an add to set on the matching documents.

Examples:

Add to set on all matching.

Person.where(:name => "Alex").add_to_set(:aliases, "value")

Parameters:

  • field (String)

    The field to add to.

  • value (Object)

    The value to add.

Returns:

  • (Object)

    The update value.

Since:

  • 2.1.0



21
22
23
24
25
26
27
# File 'lib/mongoid/contexts/mongo.rb', line 21

def add_to_set(field, value)
  klass.collection.update(
    selector,
    { "$addToSet" => { field => value } },
    :multi => true
  )
end

#aggregateHash

Aggregate the context. 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.

Examples:

Aggreate the context.

context.aggregate

Returns:

  • (Hash)

    A Hash with field values as keys, counts as values



38
39
40
41
42
43
44
45
# File 'lib/mongoid/contexts/mongo.rb', line 38

def aggregate
  klass.collection.group(
    :key => field_list,
    :cond => selector,
    :initial => { :count => 0 },
    :reduce => Javascript.aggregate
  )
end

#avg(field) ⇒ Numeric

Get the average value for the supplied field.

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 averages.

Examples:

Get the average for a field.

context.avg(:age)

Parameters:

  • field (Symbol)

    The field to get the average for.

Returns:

  • (Numeric)

    A numeric value that is the average.



60
61
62
63
# File 'lib/mongoid/contexts/mongo.rb', line 60

def avg(field)
  total = sum(field)
  total ? (total / count) : nil
end

#blank?true, false Also known as: empty?

Determine if the context is empty or blank given the criteria. Will perform a quick has_one asking only for the id.

Examples:

Is the context empty?

context.blank?a

Returns:

  • (true, false)

    True if blank.



72
73
74
# File 'lib/mongoid/contexts/mongo.rb', line 72

def blank?
  klass.collection.find_one(selector, { :fields => [ :_id ] }).nil?
end

#count(extras = false) ⇒ Integer Also known as: size, length

Get the count of matching documents in the database for the context.

Examples:

Get the count without skip and limit taken into consideration.

context.count

Get the count with skip and limit applied.

context.count(true)

Parameters:

  • extras (Boolean) (defaults to: false)

    True to inclued previous skip/limit statements in the count; false to ignore them. Defaults to ‘false`.

Returns:

  • (Integer)

    The count of documents.



89
90
91
92
93
94
95
# File 'lib/mongoid/contexts/mongo.rb', line 89

def count(extras = false)
  if cached?
    @count ||= collection.find(selector, process_options).count(extras)
  else
    collection.find(selector, process_options).count(extras)
  end
end

#delete_allInteger Also known as: delete

Delete all the documents in the database matching the selector.

Examples:

Delete the documents.

context.delete_all

Returns:

  • (Integer)

    The number of documents deleted.

Since:

  • 2.0.0.rc.1



107
108
109
# File 'lib/mongoid/contexts/mongo.rb', line 107

def delete_all
  klass.delete_all(:conditions => selector)
end

#destroy_allInteger Also known as: destroy

Destroy all the documents in the database matching the selector.

Examples:

Destroy the documents.

context.destroy_all

Returns:

  • (Integer)

    The number of documents destroyed.

Since:

  • 2.0.0.rc.1



120
121
122
# File 'lib/mongoid/contexts/mongo.rb', line 120

def destroy_all
  klass.destroy_all(:conditions => selector)
end

#distinct(field) ⇒ Array<Object>

Gets an array of distinct values for the supplied field across the entire collection or the susbset given the criteria.

Examples:

Get the distinct values.

context.distinct(:title)

Parameters:

  • field (Symbol)

    The field to get the values for.

Returns:

  • (Array<Object>)

    The distinct values for the field.



134
135
136
# File 'lib/mongoid/contexts/mongo.rb', line 134

def distinct(field)
  klass.collection.distinct(field, selector)
end

#eager_load(docs) ⇒ Object

Eager load the inclusions for the provided documents.

Examples:

Eager load the inclusions.

context.eager_load(docs)

Parameters:

Since:

  • 2.4.1



146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/mongoid/contexts/mongo.rb', line 146

def eager_load(docs)
  criteria.inclusions.reject! do ||
    unless docs.empty?
      parent_ids = docs.map(&:id)
      if .macro == :referenced_in
        child_ids = load_ids(.foreign_key)
        .eager_load(child_ids)
      else
        .eager_load(parent_ids)
      end
    end
  end
end

#executeCursor

Execute the context. This will take the 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.

Examples:

Execute the criteria on the context.

context.execute

Returns:

  • (Cursor)

    An enumerable Cursor of results.



169
170
171
172
173
174
175
176
177
178
# File 'lib/mongoid/contexts/mongo.rb', line 169

def execute
  collection, options = klass.collection, process_options
  if criteria.inclusions.any?
    collection.find(selector, options).entries.tap do |docs|
      eager_load(docs)
    end
  else
    collection.find(selector, options)
  end
end

#firstDocument Also known as: one

Return the first result for the Context.

Examples:

Get the first document.

context.one

Returns:

  • (Document)

    The first document in the collection.



204
205
206
207
208
209
210
211
212
# File 'lib/mongoid/contexts/mongo.rb', line 204

def first
  attributes = klass.collection.find_one(selector, options_with_default_sorting)
  return nil unless attributes
  selecting do
    Mongoid::Factory.from_db(klass, attributes).tap do |doc|
      eager_load([ doc ]) if criteria.inclusions.any?
    end
  end
end

#groupHash

Groups the context. 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.

Examples:

Get the criteria as a group.

context.group

Returns:

  • (Hash)

    Hash with field values as keys, arrays of documents as values.



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

def group
  klass.collection.group(
    :key => field_list,
    :cond => selector,
    :initial => { :group => [] },
    :reduce => Javascript.group
  ).collect do |docs|
    docs["group"] = docs["group"].collect do |attrs|
      Mongoid::Factory.from_db(klass, attrs)
    end
    docs
  end
end

#iterate(&block) ⇒ Object

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 results.

context.iterate { |doc| p doc }


258
259
260
261
262
263
264
265
# File 'lib/mongoid/contexts/mongo.rb', line 258

def iterate(&block)
  selecting do
    return caching(&block) if cached?
    if block_given?
      execute.each { |doc| yield doc }
    end
  end
end

#lastDocument

Return the last result for the Context. Essentially does a find_one on the collection with the sorting reversed. If no sorting parameters have been provided it will default to ids.

Examples:

Get the last document.

context.last

Returns:

  • (Document)

    The last document in the collection.



275
276
277
278
279
280
281
282
283
284
285
# File 'lib/mongoid/contexts/mongo.rb', line 275

def last
  opts = options_with_default_sorting
  opts[:sort] = opts[:sort].map{ |option| [ option[0], option[1].invert ] }.uniq
  attributes = klass.collection.find_one(selector, opts)
  return nil unless attributes
  selecting do
    Mongoid::Factory.from_db(klass, attributes).tap do |doc|
      eager_load([ doc ]) if criteria.inclusions.any?
    end
  end
end

#load_ids(key) ⇒ Array<String, BSON::ObjectId>

Loads an array of ids only for the current criteria. Used by eager loading to determine the documents to load.

Examples:

Load the related ids.

criteria.load_ids("person_id")

Parameters:

  • key (String)

    The id or foriegn key string.

Returns:

Since:

  • 2.2.0



191
192
193
194
195
196
# File 'lib/mongoid/contexts/mongo.rb', line 191

def load_ids(key)
  klass.collection.driver.find(
    selector,
    process_options.merge({ :fields => { key => 1 }})
  ).map { |doc| doc[key] }
end

#max(field) ⇒ Numeric

Return the max value for a field.

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 sums.

Examples:

Get the max value.

context.max(:age)

Parameters:

  • field (Symbol)

    The field to get the max for.

Returns:

  • (Numeric)

    A numeric max value.



300
301
302
# File 'lib/mongoid/contexts/mongo.rb', line 300

def max(field)
  grouped(:max, field.to_s, Javascript.max, Javascript.max_finalize)
end

#min(field) ⇒ Numeric

Return the min value for a field.

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 sums.

Examples:

Get the min value.

context.min(:age)

Parameters:

  • field (Symbol)

    The field to get the min for.

Returns:

  • (Numeric)

    A numeric minimum value.



317
318
319
# File 'lib/mongoid/contexts/mongo.rb', line 317

def min(field)
  grouped(:min, field.to_s, Javascript.min, Javascript.min_finalize)
end

#pull(field, value) ⇒ Object

Perform a pull on the matching documents.

Examples:

Pull on all matching.

Person.where(:name => "Alex").pull(:aliases, "value")

Parameters:

  • field (String)

    The field to pull from.

  • value (Object)

    The value to pull.

Returns:

  • (Object)

    The update value.

Since:

  • 2.1.0



332
333
334
335
336
337
338
# File 'lib/mongoid/contexts/mongo.rb', line 332

def pull(field, value)
  klass.collection.update(
    selector,
    { "$pull" => { field => value } },
    :multi => true
  )
end

#shiftDocument

Return the first result for the Context and skip it for successive calls.

Examples:

Get the first document and shift.

context.shift

Returns:

  • (Document)

    The first document in the collection.



347
348
349
# File 'lib/mongoid/contexts/mongo.rb', line 347

def shift
  first.tap { criteria.skip((options[:skip] || 0) + 1) }
end

#sum(field) ⇒ Numeric

Sum the context.

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 sums.

Examples:

Get the sum for a field.

context.sum(:age)

Parameters:

  • field (Symbol)

    The field who’s values to sum.

Returns:

  • (Numeric)

    A numeric value that is the sum.



364
365
366
# File 'lib/mongoid/contexts/mongo.rb', line 364

def sum(field)
  grouped(:sum, field.to_s, Javascript.sum, Javascript.sum_finalize)
end

#update_all(attributes = {}) ⇒ Object Also known as: update

Very basic update that will perform a simple atomic $set of the attributes provided in the hash. Can be expanded to later for more robust functionality.

Examples:

Update all matching documents.

context.update_all(:title => "Sir")

Parameters:

  • attributes (Hash) (defaults to: {})

    The sets to perform.

Since:

  • 2.0.0.rc.4



378
379
380
381
382
383
384
385
386
# File 'lib/mongoid/contexts/mongo.rb', line 378

def update_all(attributes = {})
  klass.collection.update(
    selector,
    { "$set" => attributes },
    Safety.merge_safety_options(:multi => true)
  ).tap do
    Threaded.clear_options!
  end
end