Class: Mongoid::Contextual::Mongo

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Atomic, Aggregable::Mongo, Queryable, Relations::Eager
Defined in:
lib/mongoid/contextual/mongo.rb

Constant Summary

OPTIONS =

Options constant.

Since:

  • 5.0.0

[ :hint, :limit, :skip, :sort, :batch_size, :max_scan, :snapshot, :comment, :read ].freeze

Constants included from Atomic

Atomic::UPDATES

Instance Attribute Summary collapse

Attributes included from Queryable

#collection, #collection The collection to query against., #criteria, #criteria The criteria for the context., #klass, #klass The klass for the criteria.

Attributes included from Relations::Eager

#eager_loaded

Instance Method Summary collapse

Methods included from Queryable

#blank?

Methods included from Relations::Eager

#eager_load, #eager_load_one, #eager_loadable?, #preload, #with_eager_loading

Methods included from Atomic

#add_atomic_pull, #add_atomic_unset, #atomic_array_add_to_sets, #atomic_array_pulls, #atomic_array_pushes, #atomic_attribute_name, #atomic_delete_modifier, #atomic_insert_modifier, #atomic_path, #atomic_paths, #atomic_position, #atomic_pulls, #atomic_pushes, #atomic_sets, #atomic_unsets, #atomic_updates, #delayed_atomic_pulls, #delayed_atomic_sets, #delayed_atomic_unsets, #flag_as_destroyed, #flagged_destroys, #process_flagged_destroys

Methods included from Aggregable::Mongo

#aggregates, #avg, #max, #min, #sum

Constructor Details

#initialize(criteria) ⇒ Mongo

Create the new Mongo context. This delegates operations to the underlying driver.

Examples:

Create the new context.

Mongo.new(criteria)

Since:

  • 3.0.0



311
312
313
314
315
316
317
# File 'lib/mongoid/contextual/mongo.rb', line 311

def initialize(criteria)
  @criteria, @klass, @cache = criteria, criteria.klass, criteria.options[:cache]
  @collection = @klass.with(criteria.persistence_options || {}).collection
  criteria.send(:merge_type_selection)
  @view = collection.find(criteria.selector)
  apply_options
end

Instance Attribute Details

#viewObject (readonly)

Returns the value of attribute view



24
25
26
# File 'lib/mongoid/contextual/mongo.rb', line 24

def view
  @view
end

#view The Mongo collection view.(TheMongocollectionview.) ⇒ Object (readonly)



24
# File 'lib/mongoid/contextual/mongo.rb', line 24

attr_reader :view

Instance Method Details

#cached?true, false

Is the context cached?

Examples:

Is the context cached?

context.cached?

Since:

  • 3.0.0



34
35
36
# File 'lib/mongoid/contextual/mongo.rb', line 34

def cached?
  !!@cache
end

#count(options = {}, &block) ⇒ Integer

Get the number of documents matching the query.

Examples:

Get the number of matching documents.

context.count

Get the count of documents with the provided options.

context.count(limit: 1)

Get the count for where the provided block is true.

context.count do |doc|
  doc.likes > 1
end

Since:

  • 3.0.0



57
58
59
60
# File 'lib/mongoid/contextual/mongo.rb', line 57

def count(options = {}, &block)
  return super(&block) if block_given?
  try_cache(:count) { view.count(options) }
end

#deletenil Also known as: delete_all

Delete all documents in the database that match the selector.

Examples:

Delete all the documents.

context.delete

Since:

  • 3.0.0



70
71
72
73
74
# File 'lib/mongoid/contextual/mongo.rb', line 70

def delete
  self.count.tap do
    view.delete_many
  end
end

#destroynil Also known as: destroy_all

Destroy all documents in the database that match the selector.

Examples:

Destroy all the documents.

context.destroy

Since:

  • 3.0.0



85
86
87
88
89
90
91
# File 'lib/mongoid/contextual/mongo.rb', line 85

def destroy
  destroyed = self.count
  each do |doc|
    doc.destroy
  end
  destroyed
end

#distinct(field) ⇒ Array<Object>

Get the distinct values in the db for the provided field.

Examples:

Get the distinct values.

context.distinct(:name)

Since:

  • 3.0.0



104
105
106
# File 'lib/mongoid/contextual/mongo.rb', line 104

def distinct(field)
  view.distinct(klass.database_field_name(field))
end

#each(&block) ⇒ Enumerator

Iterate over the context. If provided a block, yield to a Mongoid document for each, otherwise return an enum.

Examples:

Iterate over the context.

context.each do |doc|
  puts doc.name
end

Since:

  • 3.0.0



119
120
121
122
123
124
125
126
127
128
129
# File 'lib/mongoid/contextual/mongo.rb', line 119

def each(&block)
  if block_given?
    documents_for_iteration.each do |doc|
      yield_document(doc, &block)
    end
    @cache_loaded = true
    self
  else
    to_enum
  end
end

#exists?true, false

Note:

We don't use count here since Mongo does not use counted b-tree indexes, unless a count is already cached then that is used to determine the value.

Do any documents exist for the context.

Examples:

Do any documents exist for the context.

context.exists?

Since:

  • 3.0.0



143
144
145
146
147
148
149
150
# File 'lib/mongoid/contextual/mongo.rb', line 143

def exists?
  return !documents.empty? if cached? && cache_loaded?
  return @count > 0 if instance_variable_defined?(:@count)

  try_cache(:exists) do
    !!(view.projection(_id: 1).limit(1).first)
  end
end

#explainHash

Run an explain on the criteria.

Examples:

Explain the criteria.

Band.where(name: "Depeche Mode").explain

Since:

  • 3.0.0



160
161
162
# File 'lib/mongoid/contextual/mongo.rb', line 160

def explain
  view.explain
end

#find_firstObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return the first result without applying sort

Since:

  • 4.0.2



250
251
252
253
# File 'lib/mongoid/contextual/mongo.rb', line 250

def find_first
  return documents.first if cached? && cache_loaded?
  with_eager_loading(view.first)
end

#find_one_and_deleteDocument

Execute the find and modify command, used for MongoDB's $findAndModify. This deletes the found document.

Examples:

Execute the command.

context.find_one_and_delete

Since:

  • 5.0.0



217
218
219
220
221
# File 'lib/mongoid/contextual/mongo.rb', line 217

def find_one_and_delete
  if doc = view.find_one_and_delete
    Factory.from_db(klass, doc)
  end
end

#find_one_and_replace(replacement, options = {}) ⇒ Document

Execute the find and modify command, used for MongoDB's $findAndModify.

Examples:

Execute the command.

context.find_one_and_update({ likes: 1 })

Options Hash (options):

  • :return_document (:before, :after)

    Return the updated document from before or after update.

  • :upsert (true, false)

    Create the document if it doesn't exist.

Since:

  • 5.0.0



202
203
204
205
206
# File 'lib/mongoid/contextual/mongo.rb', line 202

def find_one_and_replace(replacement, options = {})
  if doc = view.find_one_and_replace(replacement, options)
    Factory.from_db(klass, doc)
  end
end

#find_one_and_update(update, options = {}) ⇒ Document

Execute the find and modify command, used for MongoDB's $findAndModify.

Examples:

Execute the command.

context.find_one_and_update({ "$inc" => { likes: 1 }})

Options Hash (options):

  • :return_document (:before, :after)

    Return the updated document from before or after update.

  • :upsert (true, false)

    Create the document if it doesn't exist.

Since:

  • 5.0.0



180
181
182
183
184
# File 'lib/mongoid/contextual/mongo.rb', line 180

def find_one_and_update(update, options = {})
  if doc = view.find_one_and_update(update, options)
    Factory.from_db(klass, doc)
  end
end

#firstDocument Also known as: one

Note:

Mongoid previously added an _id sort when no sort parameters were provided explicitly by the user. This caused bad performance issues and was not expected, so #first/#last will no longer guarantee order if no sorting parameters are provided. For order guarantees - a sort must be explicitly provided.

Get the first document in the database for the criteria's selector.

Examples:

Get the first document.

context.first

Since:

  • 3.0.0



237
238
239
240
241
242
# File 'lib/mongoid/contextual/mongo.rb', line 237

def first
  return documents.first if cached? && cache_loaded?
  try_cache(:first) do
    with_eager_loading(view.first)
  end
end

#geo_near(coordinates) ⇒ GeoNear

Execute a $geoNear command against the database.

Examples:

Find documents close to 10, 10.

context.geo_near([ 10, 10 ])

Find with spherical distance.

context.geo_near([ 10, 10 ]).spherical

Find with a max distance.

context.geo_near([ 10, 10 ]).max_distance(0.5)

Provide a distance multiplier.

context.geo_near([ 10, 10 ]).distance_multiplier(1133)

Since:

  • 3.1.0



274
275
276
# File 'lib/mongoid/contextual/mongo.rb', line 274

def geo_near(coordinates)
  GeoNear.new(collection, criteria, coordinates)
end

#lastDocument

Note:

Mongoid previously added an _id sort when no sort parameters were provided explicitly by the user. This caused bad performance issues and was not expected, so #first/#last will no longer guarantee order if no sorting parameters are provided. For order guarantees - a sort must be explicitly provided.

Get the last document in the database for the criteria's selector.

Examples:

Get the last document.

context.last

Since:

  • 3.0.0



335
336
337
338
339
340
341
# File 'lib/mongoid/contextual/mongo.rb', line 335

def last
  try_cache(:last) do
    with_inverse_sorting do
      with_eager_loading(view.first)
    end
  end
end

#lengthInteger Also known as: size

Get's the number of documents matching the query selector.

Examples:

Get the length.

context.length

Since:

  • 3.0.0



351
352
353
# File 'lib/mongoid/contextual/mongo.rb', line 351

def length
  @length ||= self.count
end

#limit(value) ⇒ Mongo

Limits the number of documents that are returned from the database.

Examples:

Limit the documents.

context.limit(20)

Since:

  • 3.0.0



366
367
368
# File 'lib/mongoid/contextual/mongo.rb', line 366

def limit(value)
  @view = view.limit(value) and self
end

#map(field = nil, &block) ⇒ Array

Invoke the block for each element of Contextual. Create a new array containing the values returned by the block.

If the symbol field name is passed instead of the block, additional optimizations would be used.

Examples:

Map by some field.

context.map(:field1)


293
294
295
296
297
298
299
300
# File 'lib/mongoid/contextual/mongo.rb', line 293

def map(field = nil, &block)
  if block_given?
    super(&block)
  else
    field = field.to_sym
    criteria.only(field).map(&field.to_proc)
  end
end

#map_reduce(map, reduce) ⇒ MapReduce

Initiate a map/reduce operation from the context.

Examples:

Initiate a map/reduce.

context.map_reduce(map, reduce)

Since:

  • 3.0.0



381
382
383
# File 'lib/mongoid/contextual/mongo.rb', line 381

def map_reduce(map, reduce)
  MapReduce.new(collection, criteria, map, reduce)
end

#pluck(*fields) ⇒ Array<Object, Array>

Note:

This method will return the raw db values - it performs no custom serialization.

Pluck the single field values from the database. Will return duplicates if they exist and only works for top level fields.

Examples:

Pluck a field.

context.pluck(:_id)

Since:

  • 3.1.0



399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/mongoid/contextual/mongo.rb', line 399

def pluck(*fields)
  normalized_select = fields.inject({}) do |hash, f|
    hash[klass.database_field_name(f)] = 1
    hash
  end

  view.projection(normalized_select).map do |doc|
    if normalized_select.size == 1
      doc[normalized_select.keys.first]
    else
      normalized_select.keys.map { |n| doc[n] }
    end
  end
end

#skip(value) ⇒ Mongo

Skips the provided number of documents.

Examples:

Skip the documents.

context.skip(20)

Since:

  • 3.0.0



424
425
426
# File 'lib/mongoid/contextual/mongo.rb', line 424

def skip(value)
  @view = view.skip(value) and self
end

#sort(values = nil, &block) ⇒ Mongo

Sorts the documents by the provided spec.

Examples:

Sort the documents.

context.sort(name: -1, title: 1)

Since:

  • 3.0.0



439
440
441
442
443
444
445
446
447
448
# File 'lib/mongoid/contextual/mongo.rb', line 439

def sort(values = nil, &block)
  if block_given?
    super(&block)
  else
    # update the criteria
    @criteria = criteria.order_by(values)
    apply_option(:sort)
    self
  end
end

#update(attributes = nil) ⇒ nil, false

Update the first matching document atomically.

Examples:

Update the first matching document.

context.update({ "$set" => { name: "Smiths" }})

Since:

  • 3.0.0



460
461
462
# File 'lib/mongoid/contextual/mongo.rb', line 460

def update(attributes = nil)
  update_documents(attributes)
end

#update_all(attributes = nil) ⇒ nil, false

Update all the matching documents atomically.

Examples:

Update all the matching documents.

context.update_all({ "$set" => { name: "Smiths" }})

Since:

  • 3.0.0



474
475
476
# File 'lib/mongoid/contextual/mongo.rb', line 474

def update_all(attributes = nil)
  update_documents(attributes, :update_many)
end