Class: Mongoid::Cursor

Inherits:
Object show all
Includes:
Enumerable, Mongoid::Collections::Retry
Defined in:
lib/mongoid/cursor.rb

Overview

Mongoid wrapper of the Ruby Driver cursor.

Constant Summary collapse

OPERATIONS =

Operations on the Mongo::Cursor object that will not get overriden by the Mongoid::Cursor are defined here.

[
  :close,
  :closed?,
  :count,
  :explain,
  :fields,
  :full_collection_name,
  :hint,
  :limit,
  :order,
  :query_options_hash,
  :query_opts,
  :selector,
  :skip,
  :snapshot,
  :sort,
  :timeout
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Mongoid::Collections::Retry

#retry_on_connection_failure

Constructor Details

#initialize(klass, collection, cursor) ⇒ Cursor

Create the new Mongoid::Cursor.

Examples:

Instantiate the cursor.

Mongoid::Cursor.new(Person, cursor)

Parameters:

  • klass (Class)

    The class associated with the cursor.

  • collection (Collection)

    The Mongoid::Collection instance.

  • cursor (Mongo::Cursor)

    The Mongo::Cursor to be proxied.



63
64
65
# File 'lib/mongoid/cursor.rb', line 63

def initialize(klass, collection, cursor)
  @klass, @collection, @cursor = klass, collection, cursor
end

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



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

def collection
  @collection
end

#cursorObject (readonly)

Returns the value of attribute cursor.



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

def cursor
  @cursor
end

#klassObject (readonly)

Returns the value of attribute klass.



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

def klass
  @klass
end

Instance Method Details

#eachObject

Iterate over each document in the cursor and yield to it.

Examples:

Iterate over the cursor.

cursor.each { |doc| p doc.title }


47
48
49
50
51
52
53
# File 'lib/mongoid/cursor.rb', line 47

def each
  retry_on_connection_failure do
    while document = cursor.next_document
      yield Factory.from_db(klass, document)
    end
  end
end

#next_documentDocument

Return the next document in the cursor. Will instantiate a new Mongoid document with the attributes.

Examples:

Get the next document.

cursor.next_document

Returns:

  • (Document)

    The next document in the cursor.



74
75
76
# File 'lib/mongoid/cursor.rb', line 74

def next_document
  Mongoid::Factory.from_db(klass, cursor.next_document)
end

#to_aArray<Document>

Returns an array of all the documents in the cursor.

Examples:

Get the cursor as an array.

cursor.to_a

Returns:



84
85
86
# File 'lib/mongoid/cursor.rb', line 84

def to_a
  cursor.to_a.collect { |attrs| Mongoid::Factory.from_db(klass, attrs) }
end