Class: Mongo::Cursor
- Includes:
- Enumerable, Constants, Conversions, Logging
- Defined in:
- lib/mongo/cursor.rb
Overview
A cursor over query results. Returned objects are hashes.
Constant Summary
Constants included from Conversions
Mongo::Conversions::ASCENDING_CONVERSION, Mongo::Conversions::DESCENDING_CONVERSION
Constants included from Constants
Mongo::Constants::OP_DELETE, Mongo::Constants::OP_GET_MORE, Mongo::Constants::OP_INSERT, Mongo::Constants::OP_KILL_CURSORS, Mongo::Constants::OP_MSG, Mongo::Constants::OP_QUERY, Mongo::Constants::OP_QUERY_AWAIT_DATA, Mongo::Constants::OP_QUERY_EXHAUST, Mongo::Constants::OP_QUERY_NO_CURSOR_TIMEOUT, Mongo::Constants::OP_QUERY_OPLOG_REPLAY, Mongo::Constants::OP_QUERY_SLAVE_OK, Mongo::Constants::OP_QUERY_TAILABLE, Mongo::Constants::OP_REPLY, Mongo::Constants::OP_UPDATE, Mongo::Constants::REPLY_AWAIT_CAPABLE, Mongo::Constants::REPLY_CURSOR_NOT_FOUND, Mongo::Constants::REPLY_QUERY_FAILURE, Mongo::Constants::REPLY_SHARD_CONFIG_STALE
Instance Attribute Summary collapse
-
#collection ⇒ Object
readonly
Returns the value of attribute collection.
-
#comment ⇒ Object
readonly
Returns the value of attribute comment.
-
#cursor_id ⇒ Object
readonly
Returns the value of attribute cursor_id.
-
#fields ⇒ Object
readonly
Returns the value of attribute fields.
-
#full_collection_name ⇒ Object
readonly
Returns the value of attribute full_collection_name.
-
#hint ⇒ Object
readonly
Returns the value of attribute hint.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
-
#order ⇒ Object
readonly
Returns the value of attribute order.
-
#read ⇒ Object
readonly
Returns the value of attribute read.
-
#selector ⇒ Object
readonly
Returns the value of attribute selector.
-
#show_disk_loc ⇒ Object
readonly
Returns the value of attribute show_disk_loc.
-
#snapshot ⇒ Object
readonly
Returns the value of attribute snapshot.
-
#tag_sets ⇒ Object
readonly
Returns the value of attribute tag_sets.
-
#timeout ⇒ Object
readonly
Returns the value of attribute timeout.
-
#transformer ⇒ Object
readonly
Returns the value of attribute transformer.
Instance Method Summary collapse
-
#add_option(opt) ⇒ Integer
Add an option to the query options bitfield.
-
#alive? ⇒ Boolean
Guess whether the cursor is alive on the server.
-
#batch_size(size = nil) ⇒ Cursor
Set the batch size for server responses.
-
#close ⇒ True
Close the cursor.
-
#closed? ⇒ Boolean
Is this cursor closed?.
-
#count(skip_and_limit = false) ⇒ Integer
Get the size of the result set for this query.
-
#each { ... } ⇒ Object
Iterate over each document in this cursor, yielding it to the given block, if provided.
-
#explain ⇒ Hash
Get the explain plan for this cursor.
-
#has_next? ⇒ Boolean
Determine whether this cursor has any remaining results.
-
#initialize(collection, opts = {}) ⇒ Cursor
constructor
Create a new cursor.
-
#inspect ⇒ Object
Clean output for inspect.
-
#limit(number_to_return = nil) ⇒ Integer
Limit the number of results to be returned by this cursor.
-
#next ⇒ Hash, Nil
(also: #next_document)
Get the next document specified the cursor options.
-
#query_options_hash ⇒ Hash
Get the query options for this Cursor.
-
#query_opts ⇒ Integer
Returns an integer indicating which query options have been selected.
-
#remove_option(opt) ⇒ Integer
Remove an option from the query options bitfield.
-
#rewind! ⇒ Object
Reset this cursor on the server.
-
#skip(number_to_skip = nil) ⇒ Integer
Skips the first
number_to_skipresults of this cursor. -
#sort(order, direction = nil) ⇒ Object
Sort this cursor’s results.
-
#to_a ⇒ Array
Receive all the documents from this cursor as an array of hashes.
Methods included from Logging
#instrument, instrumenter, instrumenter=, #log, #write_logging_startup_message
Methods included from Conversions
#array_as_sort_parameters, #hash_as_sort_parameters, #sort_value, #string_as_sort_parameters
Methods included from Enumerable
Constructor Details
#initialize(collection, opts = {}) ⇒ Cursor
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.
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
# File 'lib/mongo/cursor.rb', line 40 def initialize(collection, opts={}) @cursor_id = nil @db = collection.db @collection = collection @connection = @db.connection @logger = @connection.logger # Query selector @selector = opts[:selector] || {} # Special operators that form part of $query @order = opts[:order] @explain = opts[:explain] @hint = opts[:hint] @snapshot = opts[:snapshot] @max_scan = opts.fetch(:max_scan, nil) @return_key = opts.fetch(:return_key, nil) @show_disk_loc = opts.fetch(:show_disk_loc, nil) @comment = opts[:comment] # Wire-protocol settings @fields = convert_fields_for_query(opts[:fields]) @skip = opts[:skip] || 0 @limit = opts[:limit] || 0 @tailable = opts[:tailable] || false @timeout = opts.fetch(:timeout, true) = 0 # Use this socket for the query @socket = opts[:socket] @closed = false @query_run = false @transformer = opts[:transformer] @read = opts[:read] || @collection.read Mongo::ReadPreference::validate(@read) @tag_sets = opts[:tag_sets] || @collection.tag_sets @acceptable_latency = opts[:acceptable_latency] || @collection.acceptable_latency batch_size(opts[:batch_size] || 0) @full_collection_name = "#{@collection.db.name}.#{@collection.name}" @cache = [] @returned = 0 if(!@timeout) add_option(OP_QUERY_NO_CURSOR_TIMEOUT) end if(@read != :primary) add_option(OP_QUERY_SLAVE_OK) end if(@tailable) add_option(OP_QUERY_TAILABLE) end if @collection.name =~ /^\$cmd/ || @collection.name =~ /^system/ @command = true else @command = false end end |
Instance Attribute Details
#collection ⇒ Object (readonly)
Returns the value of attribute collection.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def collection @collection end |
#comment ⇒ Object (readonly)
Returns the value of attribute comment.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def comment @comment end |
#cursor_id ⇒ Object (readonly)
Returns the value of attribute cursor_id.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def cursor_id @cursor_id end |
#fields ⇒ Object (readonly)
Returns the value of attribute fields.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def fields @fields end |
#full_collection_name ⇒ Object (readonly)
Returns the value of attribute full_collection_name.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def full_collection_name @full_collection_name end |
#hint ⇒ Object (readonly)
Returns the value of attribute hint.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def hint @hint end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def end |
#order ⇒ Object (readonly)
Returns the value of attribute order.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def order @order end |
#read ⇒ Object (readonly)
Returns the value of attribute read.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def read @read end |
#selector ⇒ Object (readonly)
Returns the value of attribute selector.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def selector @selector end |
#show_disk_loc ⇒ Object (readonly)
Returns the value of attribute show_disk_loc.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def show_disk_loc @show_disk_loc end |
#snapshot ⇒ Object (readonly)
Returns the value of attribute snapshot.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def snapshot @snapshot end |
#tag_sets ⇒ Object (readonly)
Returns the value of attribute tag_sets.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def tag_sets @tag_sets end |
#timeout ⇒ Object (readonly)
Returns the value of attribute timeout.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def timeout @timeout end |
#transformer ⇒ Object (readonly)
Returns the value of attribute transformer.
26 27 28 |
# File 'lib/mongo/cursor.rb', line 26 def transformer @transformer end |
Instance Method Details
#add_option(opt) ⇒ Integer
Add an option to the query options bitfield.
377 378 379 380 381 382 |
# File 'lib/mongo/cursor.rb', line 377 def add_option(opt) check_modifiable |= opt end |
#alive? ⇒ Boolean
Guess whether the cursor is alive on the server.
Note that this method only checks whether we have a cursor id. The cursor may still have timed out on the server. This will be indicated in the next call to Cursor#next.
111 112 113 |
# File 'lib/mongo/cursor.rb', line 111 def alive? @cursor_id && @cursor_id != 0 end |
#batch_size(size = nil) ⇒ Cursor
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.
This can not override MongoDB’s limit on the amount of data it will return to the client. Depending on server version this can be 4-16mb.
260 261 262 263 264 265 266 267 268 269 270 |
# File 'lib/mongo/cursor.rb', line 260 def batch_size(size=nil) return @batch_size unless size check_modifiable if size < 0 || size == 1 raise ArgumentError, "Invalid value for batch_size #{size}; must be 0 or > 1." else @batch_size = @limit != 0 && size > @limit ? @limit : size end self end |
#close ⇒ True
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.
336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/mongo/cursor.rb', line 336 def close if @cursor_id && @cursor_id != 0 = BSON::ByteBuffer.new([0, 0, 0, 0]) .put_int(1) .put_long(@cursor_id) log(:debug, "Cursor#close #{@cursor_id}") @connection.(Mongo::Constants::OP_KILL_CURSORS, , :socket => @socket) end @cursor_id = 0 @closed = true end |
#closed? ⇒ Boolean
Is this cursor closed?
351 352 353 |
# File 'lib/mongo/cursor.rb', line 351 def closed? @closed end |
#count(skip_and_limit = false) ⇒ Integer
Get the size of the result set for this query.
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/mongo/cursor.rb', line 177 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, :read => @read, :comment => @comment) return response['n'].to_i if Mongo::Support.ok?(response) return 0 if response['errmsg'] == "ns missing" raise OperationFailure.new("Count failed: #{response['errmsg']}", response['code'], response) end |
#each { ... } ⇒ Object
Iterate over each document in this cursor, yielding it to the given block, if provided. An Enumerator is returned if no block is given.
Iterating over an entire cursor will close it.
283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/mongo/cursor.rb', line 283 def each if block_given? || !defined?(Enumerator) while doc = self.next yield doc end else Enumerator.new do |yielder| while doc = self.next yielder.yield doc end end end end |
#explain ⇒ Hash
Get the explain plan for this cursor.
317 318 319 320 321 322 323 324 |
# File 'lib/mongo/cursor.rb', line 317 def explain c = Cursor.new(@collection, .merge(:limit => -@limit.abs, :explain => true)) explanation = c.next_document c.close explanation end |
#has_next? ⇒ Boolean
Determine whether this cursor has any remaining results.
166 167 168 |
# File 'lib/mongo/cursor.rb', line 166 def has_next? num_remaining > 0 end |
#inspect ⇒ Object
Clean output for inspect.
421 422 423 424 |
# File 'lib/mongo/cursor.rb', line 421 def inspect "<Mongo::Cursor:0x#{object_id.to_s(16)} namespace='#{@db.name}.#{@collection.name}' " + "@selector=#{@selector.inspect} @cursor_id=#{@cursor_id}>" end |
#limit(number_to_return = nil) ⇒ Integer
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.
224 225 226 227 228 229 |
# File 'lib/mongo/cursor.rb', line 224 def limit(number_to_return=nil) return @limit unless number_to_return check_modifiable @limit = number_to_return self end |
#next ⇒ Hash, Nil Also known as: next_document
Get the next document specified the cursor options.
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/mongo/cursor.rb', line 118 def next if @cache.length == 0 if @query_run && ( & OP_QUERY_EXHAUST != 0) close return nil else refresh end end 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.include?("not master") @connection.close raise ConnectionFailure.new(err, doc['code'], doc) end raise OperationFailure.new(err, doc['code'], doc) end if @transformer.nil? doc else @transformer.call(doc) if doc end end |
#query_options_hash ⇒ Hash
Get the query options for this Cursor.
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 |
# File 'lib/mongo/cursor.rb', line 404 def BSON::OrderedHash[ :selector => @selector, :fields => @fields, :skip => @skip, :limit => @limit, :order => @order, :hint => @hint, :snapshot => @snapshot, :timeout => @timeout, :max_scan => @max_scan, :return_key => @return_key, :show_disk_loc => @show_disk_loc, :comment => @comment ] end |
#query_opts ⇒ Integer
Returns an integer indicating which query options have been selected.
The MongoDB wire protocol.
361 362 363 364 365 |
# File 'lib/mongo/cursor.rb', line 361 def query_opts warn "The method Cursor#query_opts has been deprecated " + "and will removed in v2.0. Use Cursor#options instead." end |
#remove_option(opt) ⇒ Integer
Remove an option from the query options bitfield.
394 395 396 397 398 399 |
# File 'lib/mongo/cursor.rb', line 394 def remove_option(opt) check_modifiable &= ~opt end |
#rewind! ⇒ Object
Reset this cursor on the server. Cursor options, such as the query string and the values for skip and limit, are preserved.
153 154 155 156 157 158 159 160 161 |
# File 'lib/mongo/cursor.rb', line 153 def rewind! close @cache.clear @cursor_id = nil @closed = false @query_run = false @n_received = nil true end |
#skip(number_to_skip = nil) ⇒ Integer
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.
240 241 242 243 244 245 246 |
# File 'lib/mongo/cursor.rb', line 240 def skip(number_to_skip=nil) return @skip unless number_to_skip check_modifiable @skip = number_to_skip self end |
#sort(order, direction = nil) ⇒ Object
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.
207 208 209 210 211 212 |
# File 'lib/mongo/cursor.rb', line 207 def sort(order, direction=nil) check_modifiable order = [[order, direction]] unless direction.nil? @order = order self end |
#to_a ⇒ Array
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.
308 309 310 |
# File 'lib/mongo/cursor.rb', line 308 def to_a super end |