Class: Mongo::Cursor

Inherits:
Object show all
Includes:
Enumerable, Conversions
Defined in:
lib/mongo/cursor.rb

Overview

A cursor over query results. Returned objects are hashes.

Constant Summary

Constants included from Conversions

ASCENDING_CONVERSION, DESCENDING_CONVERSION

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Methods included from Enumerable

#each_with_object

Methods included from Conversions

#array_as_sort_parameters, #sort_value, #string_as_sort_parameters

Constructor Details

- (Cursor) initialize(collection, opts = {})

Create a new cursor.

Note: cursors are created when executing queries using [Collection#find] and other similar methods. Application developers shouldn’t have to create cursors manually.

Core docs:



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/mongo/cursor.rb', line 36

def initialize(collection, opts={})
  @db         = collection.db
  @collection = collection
  @connection = @db.connection
  @logger     = @connection.logger

  @selector   = opts[:selector] || {}
  @fields     = convert_fields_for_query(opts[:fields])
  @skip       = opts[:skip]     || 0
  @limit      = opts[:limit]    || 0
  @order      = opts[:order]
  @hint       = opts[:hint]
  @snapshot   = opts[:snapshot]
  @timeout    = opts.fetch(:timeout, true)
  @explain    = opts[:explain]
  @socket     = opts[:socket]
  @tailable   = opts[:tailable] || false
  @closed       = false
  @query_run    = false
  batch_size(opts[:batch_size] || 0)

  @full_collection_name = "#{@collection.db.name}.#{@collection.name}"
  @cache        = []
  @returned     = 0

  if @collection.name =~ /^\$cmd/ || @collection.name =~ /^system/
    @command = true
  else
    @command = false
  end
end

Instance Attribute Details

- (Object) collection (readonly)

Returns the value of attribute collection



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

def collection
  @collection
end

- (Object) fields (readonly)

Returns the value of attribute fields



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

def fields
  @fields
end

- (Object) full_collection_name (readonly)

Returns the value of attribute full_collection_name



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

def full_collection_name
  @full_collection_name
end

- (Object) hint (readonly)

Returns the value of attribute hint



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

def hint
  @hint
end

- (Object) order (readonly)

Returns the value of attribute order



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

def order
  @order
end

- (Object) selector (readonly)

Returns the value of attribute selector



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

def selector
  @selector
end

- (Object) snapshot (readonly)

Returns the value of attribute snapshot



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

def snapshot
  @snapshot
end

- (Object) timeout (readonly)

Returns the value of attribute timeout



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

def timeout
  @timeout
end

Instance Method Details

- (Cursor) batch_size(size = 0)

Set the batch size for server responses.

Note that the batch size will take effect only on queries where the number to be returned is greater than 100.

Parameters:

  • (Integer) size (defaults to: 0)

    either 0 or some integer greater than 1. If 0, the server will determine the batch size.

Returns:



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

def batch_size(size=0)
  check_modifiable
  if size < 0 || size == 1
    raise ArgumentError, "Invalid value for batch_size #{size}; must be 0 or > 1."
  else
    @batch_size = size > @limit ? @limit : size
  end

  self
end

- (True) close

Close the cursor.

Note: if a cursor is read until exhausted (read until Mongo::Constants::OP_QUERY or Mongo::Constants::OP_GETMORE returns zero for the cursor id), there is no need to close it manually.

Note also: Collection#find takes an optional block argument which can be used to ensure that your cursors get closed.

Returns:

  • (True)


273
274
275
276
277
278
279
280
281
282
283
# File 'lib/mongo/cursor.rb', line 273

def close
  if @cursor_id && @cursor_id != 0
    message = BSON::ByteBuffer.new([0, 0, 0, 0])
    message.put_int(1)
    message.put_long(@cursor_id)
    @logger.debug("MONGODB cursor.close #{@cursor_id}") if @logger
    @connection.send_message(Mongo::Constants::OP_KILL_CURSORS, message, nil)
  end
  @cursor_id = 0
  @closed    = true
end

- (Boolean) closed?

Is this cursor closed?

Returns:

  • (Boolean)


288
# File 'lib/mongo/cursor.rb', line 288

def closed?; @closed end

- (Integer) count(skip_and_limit = false)

Get the size of the result set for this query.

Parameters:

  • (Boolean) whether

    of not to take notice of skip and limit

Returns:

  • (Integer)

    the number of objects in the result set for this query.

Raises:



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

def count(skip_and_limit = false)
  command = BSON::OrderedHash["count",  @collection.name, "query",  @selector]

  if skip_and_limit
    command.merge!(BSON::OrderedHash["limit", @limit]) if @limit != 0
    command.merge!(BSON::OrderedHash["skip", @skip]) if @skip != 0
  end

  command.merge!(BSON::OrderedHash["fields", @fields])

  response = @db.command(command)
  return response['n'].to_i if Mongo::Support.ok?(response)
  return 0 if response['errmsg'] == "ns missing"
  raise OperationFailure, "Count failed: #{response['errmsg']}"
end

- (Object) each { ... }

Iterate over each document in this cursor, yielding it to the given block.

Iterating over an entire cursor will close it.

Examples:

if ‘comments’ represents a collection of comments:

comments.find.each do |doc|
  puts doc['user']
end

Yields:

  • passes each document to a block for processing.



225
226
227
228
229
230
231
232
# File 'lib/mongo/cursor.rb', line 225

def each
  #num_returned = 0
  #while has_next? && (@limit <= 0 || num_returned < @limit)
  while doc = next_document
    yield doc #next_document
    #num_returned += 1
  end
end

- (Hash) explain

Get the explain plan for this cursor.

Returns:

  • (Hash)

    a document containing the explain plan for this cursor.

Core docs:



255
256
257
258
259
260
261
# File 'lib/mongo/cursor.rb', line 255

def explain
  c = Cursor.new(@collection, query_options_hash.merge(:limit => -@limit.abs, :explain => true))
  explanation = c.next_document
  c.close

  explanation
end

- (Boolean) has_next?

Determine whether this cursor has any remaining results.

Returns:

  • (Boolean)


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

def has_next?
  num_remaining > 0
end

- (Object) inspect

Clean output for inspect.



319
320
321
322
# File 'lib/mongo/cursor.rb', line 319

def inspect
  "<Mongo::Cursor:0x#{object_id.to_s(16)} namespace='#{@db.name}.#{@collection.name}' " +
    "@selector=#{@selector.inspect}>"
end

- (Integer) limit(number_to_return = nil)

Limit the number of results to be returned by this cursor.

This method overrides any limit specified in the Collection#find method, and only the last limit applied has an effect.

Returns:

  • (Integer)

    the current number_to_return if no parameter is given.

Raises:

Core docs:



169
170
171
172
173
174
175
# File 'lib/mongo/cursor.rb', line 169

def limit(number_to_return=nil)
  return @limit unless number_to_return
  check_modifiable

  @limit = number_to_return
  self
end

- (Hash, Nil) next_document

Get the next document specified the cursor options.

Returns:

  • (Hash, Nil)

    the next document or Nil if no documents remain.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/mongo/cursor.rb', line 71

def next_document
  refresh if @cache.length == 0
  doc = @cache.shift

  if doc && doc['$err']
    err = doc['$err']

    # If the server has stopped being the master (e.g., it's one of a
    # pair but it has died or something like that) then we close that
    # connection. The next request will re-open on master server.
    if err == "not master"
      @connection.close
      raise ConnectionFailure, err
    end

    raise OperationFailure, err
  end

  doc
end

- (Hash) query_options_hash

Get the query options for this Cursor.

Returns:



307
308
309
310
311
312
313
314
315
316
# File 'lib/mongo/cursor.rb', line 307

def query_options_hash
  { :selector => @selector,
    :fields   => @fields,
    :skip     => @skip_num,
    :limit    => @limit_num,
    :order    => @order,
    :hint     => @hint,
    :snapshot => @snapshot,
    :timeout  => @timeout }
end

- (Integer) query_opts

Returns an integer indicating which query options have been selected.

The MongoDB wire protocol.



296
297
298
299
300
301
302
# File 'lib/mongo/cursor.rb', line 296

def query_opts
  opts     = 0
  opts    |= Mongo::Constants::OP_QUERY_NO_CURSOR_TIMEOUT unless @timeout
  opts    |= Mongo::Constants::OP_QUERY_SLAVE_OK if @connection.slave_ok?
  opts    |= Mongo::Constants::OP_QUERY_TAILABLE if @tailable
  opts
end

- (Object) rewind!

Reset this cursor on the server. Cursor options, such as the query string and the values for skip and limit, are preserved.



94
95
96
97
98
99
100
101
102
# File 'lib/mongo/cursor.rb', line 94

def rewind!
  close
  @cache.clear
  @cursor_id  = nil
  @closed     = false
  @query_run  = false
  @n_received = nil
  true
end

- (Integer) skip(number_to_skip = nil)

Skips the first number_to_skip results of this cursor. Returns the current number_to_skip if no parameter is given.

This method overrides any skip specified in the Collection#find method, and only the last skip applied has an effect.

Returns:

  • (Integer)

Raises:



186
187
188
189
190
191
192
# File 'lib/mongo/cursor.rb', line 186

def skip(number_to_skip=nil)
  return @skip unless number_to_skip
  check_modifiable

  @skip = number_to_skip
  self
end

- (Object) sort(key_or_list, direction = nil)

Sort this cursor’s results.

This method overrides any sort order specified in the Collection#find method, and only the last sort applied has an effect.

Parameters:

  • (Symbol, Array) key_or_list

    either 1) a key to sort by or 2) an array of [key, direction] pairs to sort by. Direction should be specified as Mongo::ASCENDING (or :ascending / :asc) or Mongo::DESCENDING (or :descending / :desc)

Raises:



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

def sort(key_or_list, direction=nil)
  check_modifiable

  if !direction.nil?
    order = [[key_or_list, direction]]
  else
    order = key_or_list
  end

  @order = order
  self
end

- (Array) to_a

Receive all the documents from this cursor as an array of hashes.

Notes:

If you’ve already started iterating over the cursor, the array returned by this method contains only the remaining documents. See Cursor#rewind! if you need to reset the cursor.

Use of this method is discouraged - in most cases, it’s much more efficient to retrieve documents as you need them by iterating over the cursor.

Returns:

  • (Array)

    an array of documents.



246
247
248
# File 'lib/mongo/cursor.rb', line 246

def to_a
  super
end