Class: Mongo::Cursor
- 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
Mongo::Conversions::ASCENDING_CONVERSION, Mongo::Conversions::DESCENDING_CONVERSION
Instance Attribute Summary collapse
-
#collection ⇒ Object
readonly
Returns the value of attribute collection.
-
#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.
-
#order ⇒ Object
readonly
Returns the value of attribute order.
-
#selector ⇒ Object
readonly
Returns the value of attribute selector.
-
#snapshot ⇒ Object
readonly
Returns the value of attribute snapshot.
-
#timeout ⇒ Object
readonly
Returns the value of attribute timeout.
Instance Method Summary collapse
-
#batch_size(size = 0) ⇒ 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.
-
#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_document ⇒ Hash, Nil
(also: #next)
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.
-
#rewind! ⇒ Object
Reset this cursor on the server.
-
#skip(number_to_skip = nil) ⇒ Integer
Skips the first
number_to_skip
results of this cursor. -
#sort(key_or_list, 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 Enumerable
Methods included from Conversions
#array_as_sort_parameters, #sort_value, #string_as_sort_parameters
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.
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
#collection ⇒ Object (readonly)
Returns the value of attribute collection.
24 25 26 |
# File 'lib/mongo/cursor.rb', line 24 def collection @collection end |
#fields ⇒ Object (readonly)
Returns the value of attribute fields.
24 25 26 |
# File 'lib/mongo/cursor.rb', line 24 def fields @fields end |
#full_collection_name ⇒ Object (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 |
#hint ⇒ Object (readonly)
Returns the value of attribute hint.
24 25 26 |
# File 'lib/mongo/cursor.rb', line 24 def hint @hint end |
#order ⇒ Object (readonly)
Returns the value of attribute order.
24 25 26 |
# File 'lib/mongo/cursor.rb', line 24 def order @order end |
#selector ⇒ Object (readonly)
Returns the value of attribute selector.
24 25 26 |
# File 'lib/mongo/cursor.rb', line 24 def selector @selector end |
#snapshot ⇒ Object (readonly)
Returns the value of attribute snapshot.
24 25 26 |
# File 'lib/mongo/cursor.rb', line 24 def snapshot @snapshot end |
#timeout ⇒ Object (readonly)
Returns the value of attribute timeout.
24 25 26 |
# File 'lib/mongo/cursor.rb', line 24 def timeout @timeout end |
Instance Method Details
#batch_size(size = 0) ⇒ 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.
204 205 206 207 208 209 210 211 212 213 |
# File 'lib/mongo/cursor.rb', line 204 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 |
#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.
274 275 276 277 278 279 280 281 282 283 284 |
# File 'lib/mongo/cursor.rb', line 274 def close if @cursor_id && @cursor_id != 0 = BSON::ByteBuffer.new([0, 0, 0, 0]) .put_int(1) .put_long(@cursor_id) @logger.debug("MONGODB cursor.close #{@cursor_id}") if @logger @connection.(Mongo::Constants::OP_KILL_CURSORS, , nil) end @cursor_id = 0 @closed = true end |
#closed? ⇒ Boolean
Is this cursor closed?
289 |
# File 'lib/mongo/cursor.rb', line 289 def closed?; @closed; end |
#count(skip_and_limit = false) ⇒ Integer
Get the size of the result set for this query.
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
# File 'lib/mongo/cursor.rb', line 119 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 |
#each { ... } ⇒ Object
Iterate over each document in this cursor, yielding it to the given block.
Iterating over an entire cursor will close it.
226 227 228 229 230 231 232 233 |
# File 'lib/mongo/cursor.rb', line 226 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 |
#explain ⇒ Hash
Get the explain plan for this cursor.
256 257 258 259 260 261 262 |
# File 'lib/mongo/cursor.rb', line 256 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.
108 109 110 |
# File 'lib/mongo/cursor.rb', line 108 def has_next? num_remaining > 0 end |
#inspect ⇒ Object
Clean output for inspect.
320 321 322 323 |
# File 'lib/mongo/cursor.rb', line 320 def inspect "<Mongo::Cursor:0x#{object_id.to_s(16)} namespace='#{@db.name}.#{@collection.name}' " + "@selector=#{@selector.inspect}>" 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.
170 171 172 173 174 175 176 |
# File 'lib/mongo/cursor.rb', line 170 def limit(number_to_return=nil) return @limit unless number_to_return check_modifiable @limit = number_to_return self end |
#next_document ⇒ Hash, Nil Also known as: next
Get the next document specified the cursor options.
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 |
#query_options_hash ⇒ Hash
Get the query options for this Cursor.
308 309 310 311 312 313 314 315 316 317 |
# File 'lib/mongo/cursor.rb', line 308 def { :selector => @selector, :fields => @fields, :skip => @skip_num, :limit => @limit_num, :order => @order, :hint => @hint, :snapshot => @snapshot, :timeout => @timeout } end |
#query_opts ⇒ Integer
Returns an integer indicating which query options have been selected.
The MongoDB wire protocol.
297 298 299 300 301 302 303 |
# File 'lib/mongo/cursor.rb', line 297 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 |
#rewind! ⇒ Object
Reset this cursor on the server. Cursor options, such as the query string and the values for skip and limit, are preserved.
95 96 97 98 99 100 101 102 103 |
# File 'lib/mongo/cursor.rb', line 95 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.
187 188 189 190 191 192 193 |
# File 'lib/mongo/cursor.rb', line 187 def skip(number_to_skip=nil) return @skip unless number_to_skip check_modifiable @skip = number_to_skip self end |
#sort(key_or_list, 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.
147 148 149 150 151 152 153 154 155 156 157 158 |
# File 'lib/mongo/cursor.rb', line 147 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 |
#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.
247 248 249 |
# File 'lib/mongo/cursor.rb', line 247 def to_a super end |