Class: Mongoid::Contextual::Mongo

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

Constant Summary

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 Eager

#eager_loaded, #eager_loaded Has the context been eager loaded?

Instance Method Summary collapse

Methods included from Queryable

#blank?

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_selector, #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 - in Mongoid’s case Moped.

Examples:

Create the new context.

Mongo.new(criteria)

Parameters:

Since:

  • 3.0.0



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

def initialize(criteria)
  @criteria, @klass, @cache = criteria, criteria.klass, criteria.options[:cache]
  @collection = klass.collection
  criteria.send(:merge_type_selection)
  @query = collection.find(criteria.selector)
  apply_options
end

Instance Attribute Details

#queryObject (readonly)

Returns the value of attribute query.



20
21
22
# File 'lib/mongoid/contextual/mongo.rb', line 20

def query
  @query
end

#query The Moped query.(TheMopedquery.) ⇒ Object (readonly)



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

attr_reader :query

Instance Method Details

#cached?true, false

Is the context cached?

Examples:

Is the context cached?

context.cached?

Returns:

  • (true, false)

    If the context is cached.

Since:

  • 3.0.0



30
31
32
# File 'lib/mongoid/contextual/mongo.rb', line 30

def cached?
  !!@cache
end

#count(document = false, &block) ⇒ Integer

Get the number of documents matching the query.

Examples:

Get the number of matching documents.

context.count

Get the count of documents matching the provided.

context.count(document)

Get the count for where the provided block is true.

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

Parameters:

  • document (Document) (defaults to: false)

    A document to match or true if wanting skip and limit to be factored into the count.

Returns:

  • (Integer)

    The number of matches.

Since:

  • 3.0.0



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

def count(document = false, &block)
  return super(&block) if block_given?
  if document.is_a?(Document)
    return collection.find(criteria.and(_id: document.id).selector).count
  end
  return query.count(document) if document
  cached? ? @count ||= query.count : query.count
end

#deletenil Also known as: delete_all

Delete all documents in the database that match the selector.

Examples:

Delete all the documents.

context.delete

Returns:

  • (nil)

    Nil.

Since:

  • 3.0.0



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

def delete
  self.count.tap do
    query.remove_all
  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

Returns:

  • (nil)

    Nil.

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)

Parameters:

  • field (String, Symbol)

    The name of the field.

Returns:

  • (Array<Object>)

    The distinct values for the field.

Since:

  • 3.0.0



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

def distinct(field)
  query.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

Returns:

  • (Enumerator)

    The enumerator.

Since:

  • 3.0.0



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

def each(&block)
  if block_given?
    selecting do
      documents_for_iteration.each do |doc|
        yield_document(doc, &block)
      end
      @cache_loaded = true
      eager_loadable? ? docs : self
    end
  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?

Returns:

  • (true, false)

    If the count is more than zero.

Since:

  • 3.0.0



145
146
147
# File 'lib/mongoid/contextual/mongo.rb', line 145

def exists?
  @exists ||= check_existence
end

#explainHash

Run an explain on the criteria.

Examples:

Explain the criteria.

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

Returns:

  • (Hash)

    The explain result.

Since:

  • 3.0.0



157
158
159
# File 'lib/mongoid/contextual/mongo.rb', line 157

def explain
  query.explain
end

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

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

Examples:

Execute the command.

context.find_and_modify({ "$inc" => { likes: 1 }}, new: true)

Parameters:

  • update (Hash)

    The updates.

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

    The command options.

Options Hash (options):

  • :new (true, false)

    Return the updated document.

  • :remove (true, false)

    Delete the first document.

  • :upsert (true, false)

    Create the document if it doesn’t exist.

Returns:

  • (Document)

    The result of the command.

Since:

  • 3.0.0



177
178
179
180
181
# File 'lib/mongoid/contextual/mongo.rb', line 177

def find_and_modify(update, options = {})
  if doc = FindAndModify.new(collection, criteria, update, options).result
    Factory.from_db(klass, doc)
  end
end

#firstDocument Also known as: one

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

Examples:

Get the first document.

context.first

Returns:

Since:

  • 3.0.0



191
192
193
194
195
196
197
198
199
# File 'lib/mongoid/contextual/mongo.rb', line 191

def first
  if cached? && cache_loaded?
    documents.first
  else
    with_sorting do
      with_eager_loading(query.first)
    end
  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)

Parameters:

  • coordinates (Array<Float>)

    The coordinates.

Returns:

  • (GeoNear)

    The GeoNear command.

Since:

  • 3.1.0



221
222
223
# File 'lib/mongoid/contextual/mongo.rb', line 221

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

#lastDocument

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

Examples:

Get the last document.

context.last

Returns:

Since:

  • 3.0.0



276
277
278
279
280
# File 'lib/mongoid/contextual/mongo.rb', line 276

def last
  with_inverse_sorting do
    with_eager_loading(query.first)
  end
end

#lengthInteger Also known as: size

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

Examples:

Get the length.

context.length

Returns:

  • (Integer)

    The number of documents.

Since:

  • 3.0.0



290
291
292
# File 'lib/mongoid/contextual/mongo.rb', line 290

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)

Parameters:

  • value (Integer)

    The number of documents to return.

Returns:

  • (Mongo)

    The context.

Since:

  • 3.0.0



305
306
307
# File 'lib/mongoid/contextual/mongo.rb', line 305

def limit(value)
  query.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)

Parameters:

  • field (Symbol) (defaults to: nil)

    The field name.

Returns:

  • (Array)

    The result of mapping.



240
241
242
243
244
245
246
247
# File 'lib/mongoid/contextual/mongo.rb', line 240

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)

Parameters:

  • map (String)

    The map js function.

  • reduce (String)

    The reduce js function.

Returns:

  • (MapReduce)

    The map/reduce lazy wrapper.

Since:

  • 3.0.0



320
321
322
# File 'lib/mongoid/contextual/mongo.rb', line 320

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

#pluck(field) ⇒ Array<Object>

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)

Parameters:

  • field (String, Symbol)

    The field to pluck.

Returns:

  • (Array<Object>)

    The plucked values.

Since:

  • 3.1.0



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

def pluck(field)
  normalized = klass.database_field_name(field)
  query.dup.select(normalized => 1).map{ |doc| doc[normalized] }.compact
end

#skip(value) ⇒ Mongo

Skips the provided number of documents.

Examples:

Skip the documents.

context.skip(20)

Parameters:

  • value (Integer)

    The number of documents to skip.

Returns:

  • (Mongo)

    The context.

Since:

  • 3.0.0



353
354
355
# File 'lib/mongoid/contextual/mongo.rb', line 353

def skip(value)
  query.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)

Parameters:

  • values (Hash) (defaults to: nil)

    The sorting values as field/direction(1/-1) pairs.

Returns:

  • (Mongo)

    The context.

Since:

  • 3.0.0



368
369
370
371
372
373
374
375
376
377
# File 'lib/mongoid/contextual/mongo.rb', line 368

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" }})

Parameters:

  • attributes (Hash) (defaults to: nil)

    The new attributes for the document.

Returns:

  • (nil, false)

    False if no attributes were provided.

Since:

  • 3.0.0



389
390
391
# File 'lib/mongoid/contextual/mongo.rb', line 389

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({ "$set" => { name: "Smiths" }})

Parameters:

  • attributes (Hash) (defaults to: nil)

    The new attributes for each document.

Returns:

  • (nil, false)

    False if no attributes were provided.

Since:

  • 3.0.0



403
404
405
# File 'lib/mongoid/contextual/mongo.rb', line 403

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