Module: Mongo::Collection::View::Readable
- Included in:
- Mongo::Collection::View
- Defined in:
- lib/mongo/collection/view/readable.rb
Overview
Defines read related behavior for collection view.
Instance Method Summary collapse
-
#aggregate(pipeline, options = {}) ⇒ Aggregation
Execute an aggregation on the collection view.
-
#allow_disk_use ⇒ View
Allows the server to write temporary data to disk while executing a find operation.
-
#allow_partial_results ⇒ View
Allows the query to get partial results if some shards are down.
-
#await_data ⇒ View
Tell the query’s cursor to stay open and wait for data.
-
#batch_size(batch_size = nil) ⇒ Integer, View
The number of documents returned in each batch of results from MongoDB.
-
#comment(comment = nil) ⇒ String, View
Associate a comment with the query.
-
#count(opts = {}) ⇒ Integer
deprecated
Deprecated.
Use #count_documents or #estimated_document_count instead. However, note that the following operators will need to be substituted when switching to #count_documents:
* $where should be replaced with $expr * $near should be replaced with $geoWithin with $center * $nearSphere should be replaced with $geoWithin with $centerSphere -
#count_documents(opts = {}) ⇒ Integer
Get a count of matching documents in the collection.
-
#cursor_type(type = nil) ⇒ :tailable, ...
The type of cursor to use.
-
#distinct(field_name, opts = {}) ⇒ Array<Object>
Get a list of distinct values for a specific field.
-
#estimated_document_count(opts = {}) ⇒ Integer
Gets an estimate of the count of documents in a collection using collection metadata.
-
#hint(hint = nil) ⇒ Hash, View
The index that MongoDB will be forced to use for the query.
-
#limit(limit = nil) ⇒ Integer, View
The max number of docs to return from the query.
-
#map_reduce(map, reduce, options = {}) ⇒ MapReduce
Execute a map/reduce operation on the collection view.
-
#max_await_time_ms(max = nil) ⇒ Integer, View
A cumulative time limit in milliseconds for processing get more operations on a cursor.
-
#max_scan(value = nil) ⇒ Integer, View
deprecated
Deprecated.
This option is deprecated as of MongoDB server version 4.0.
-
#max_time_ms(max = nil) ⇒ Integer, View
A cumulative time limit in milliseconds for processing operations on a cursor.
-
#max_value(value = nil) ⇒ Hash, View
Set the maximum value to search.
-
#min_value(value = nil) ⇒ Hash, View
Set the minimum value to search.
-
#modifiers(doc = nil) ⇒ Hash, View
If called without arguments or with a nil argument, returns the legacy (OP_QUERY) server modifiers for the current view.
-
#no_cursor_timeout ⇒ View
The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use.
- #parallel_scan(cursor_count, options = {}) ⇒ Object
-
#projection(document = nil) ⇒ Hash, View
The fields to include or exclude from each doc in the result set.
-
#read(value = nil) ⇒ Symbol, View
The read preference to use for the query.
- #read_concern ⇒ Object private
- #read_preference ⇒ Object private
-
#return_key(value = nil) ⇒ true, ...
Set whether to return only the indexed field or fields.
-
#show_disk_loc(value = nil) ⇒ true, ...
(also: #show_record_id)
Set whether the disk location should be shown for each document.
-
#skip(number = nil) ⇒ Integer, View
The number of docs to skip before returning results.
-
#snapshot(value = nil) ⇒ Object
deprecated
Deprecated.
This option is deprecated as of MongoDB server version 4.0.
-
#sort(spec = nil) ⇒ Hash, View
The key and direction pairs by which the result set will be sorted.
-
#timeout_ms(timeout_ms = nil) ⇒ Integer, View
The per-operation timeout in milliseconds.
Instance Method Details
#aggregate(pipeline, options = {}) ⇒ Aggregation
Execute an aggregation on the collection view.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/mongo/collection/view/readable.rb', line 58 def aggregate(pipeline, = {}) = @options.merge() unless Mongo. aggregation = Aggregation.new(self, pipeline, ) # Because the $merge and $out pipeline stages write documents to the # collection, it is necessary to clear the cache when they are performed. # # Opt to clear the entire cache rather than one namespace because # the $out and $merge stages do not have to write to the same namespace # on which the aggregation is performed. QueryCache.clear if aggregation.write? aggregation end |
#allow_disk_use ⇒ View
Allows the server to write temporary data to disk while executing a find operation.
77 78 79 |
# File 'lib/mongo/collection/view/readable.rb', line 77 def allow_disk_use configure(:allow_disk_use, true) end |
#allow_partial_results ⇒ View
Allows the query to get partial results if some shards are down.
89 90 91 |
# File 'lib/mongo/collection/view/readable.rb', line 89 def allow_partial_results configure(:allow_partial_results, true) end |
#await_data ⇒ View
Tell the query’s cursor to stay open and wait for data.
101 102 103 |
# File 'lib/mongo/collection/view/readable.rb', line 101 def await_data configure(:await_data, true) end |
#batch_size(batch_size = nil) ⇒ Integer, View
Specifying 1 or a negative number is analogous to setting a limit.
The number of documents returned in each batch of results from MongoDB.
118 119 120 |
# File 'lib/mongo/collection/view/readable.rb', line 118 def batch_size(batch_size = nil) configure(:batch_size, batch_size) end |
#comment(comment = nil) ⇒ String, View
Set profilingLevel to 2 and the comment will be logged in the profile collection along with the query.
Associate a comment with the query.
136 137 138 |
# File 'lib/mongo/collection/view/readable.rb', line 136 def comment(comment = nil) configure(:comment, comment) end |
#count(opts = {}) ⇒ Integer
Use #count_documents or #estimated_document_count instead. However, note that the following operators will need to be substituted when switching to #count_documents:
* $where should be replaced with $expr
* $near should be replaced with $geoWithin with $center
* $nearSphere should be replaced with $geoWithin with $centerSphere
Get a count of matching documents in the collection.
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
# File 'lib/mongo/collection/view/readable.rb', line 172 def count(opts = {}) opts = @options.merge(opts) unless Mongo. cmd = { count: collection.name, query: filter } cmd[:skip] = opts[:skip] if opts[:skip] cmd[:hint] = opts[:hint] if opts[:hint] cmd[:limit] = opts[:limit] if opts[:limit] if read_concern cmd[:readConcern] = Options::Mapper.transform_values_to_strings( read_concern ) end cmd[:maxTimeMS] = opts[:max_time_ms] if opts[:max_time_ms] Mongo::Lint.validate_underscore_read_preference(opts[:read]) read_pref = opts[:read] || read_preference selector = ServerSelector.get(read_pref || server_selector) with_session(opts) do |session| context = Operation::Context.new( client: client, session: session, operation_timeouts: operation_timeouts(opts) ) operation = Operation::Count.new( selector: cmd, db_name: database.name, options: { limit: -1 }, read: read_pref, session: session, # For some reason collation was historically accepted as a # string key. Note that this isn't documented as valid usage. collation: opts[:collation] || opts['collation'] || collation, comment: opts[:comment] ) tracer.trace_operation(operation, context) do read_with_retry(session, selector, context) do |server| operation.execute( server, context: context ) end.n.to_i end end end |
#count_documents(opts = {}) ⇒ Integer
Get a count of matching documents in the collection.
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
# File 'lib/mongo/collection/view/readable.rb', line 242 def count_documents(opts = {}) opts = @options.merge(opts) unless Mongo. pipeline = [ { '$match': filter } ] pipeline << { '$skip': opts[:skip] } if opts[:skip] pipeline << { '$limit': opts[:limit] } if opts[:limit] pipeline << { '$group': { _id: 1, n: { '$sum': 1 } } } opts = opts.slice(:hint, :max_time_ms, :read, :collation, :session, :comment, :timeout_ms) opts[:collation] ||= collation first = aggregate(pipeline, opts).first return 0 unless first first['n'].to_i end |
#cursor_type(type = nil) ⇒ :tailable, ...
The type of cursor to use. Can be :tailable or :tailable_await.
665 666 667 |
# File 'lib/mongo/collection/view/readable.rb', line 665 def cursor_type(type = nil) configure(:cursor_type, type) end |
#distinct(field_name, opts = {}) ⇒ Array<Object>
Get a list of distinct values for a specific field.
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 |
# File 'lib/mongo/collection/view/readable.rb', line 344 def distinct(field_name, opts = {}) raise ArgumentError, 'Field name for distinct operation must be not nil' if field_name.nil? opts = @options.merge(opts) unless Mongo. cmd = { distinct: collection.name, key: field_name.to_s, query: filter, } cmd[:maxTimeMS] = opts[:max_time_ms] if opts[:max_time_ms] if read_concern cmd[:readConcern] = Options::Mapper.transform_values_to_strings( read_concern ) end Mongo::Lint.validate_underscore_read_preference(opts[:read]) read_pref = opts[:read] || read_preference selector = ServerSelector.get(read_pref || server_selector) with_session(opts) do |session| context = Operation::Context.new( client: client, session: session, operation_timeouts: operation_timeouts(opts) ) operation = Operation::Distinct.new( selector: cmd, db_name: database.name, options: { limit: -1 }, read: read_pref, session: session, comment: opts[:comment], # For some reason collation was historically accepted as a # string key. Note that this isn't documented as valid usage. collation: opts[:collation] || opts['collation'] || collation ) tracer.trace_operation(operation, context) do read_with_retry(session, selector, context) do |server| operation.execute( server, context: context ) end.first['values'] end end end |
#estimated_document_count(opts = {}) ⇒ Integer
Gets an estimate of the count of documents in a collection using collection metadata.
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
# File 'lib/mongo/collection/view/readable.rb', line 278 def estimated_document_count(opts = {}) unless view.filter.empty? raise ArgumentError, 'Cannot call estimated_document_count when querying with a filter' end %i[limit skip].each do |opt| if .key?(opt) || opts.key?(opt) raise ArgumentError, "Cannot call estimated_document_count when querying with #{opt}" end end opts = @options.merge(opts) unless Mongo. Mongo::Lint.validate_underscore_read_preference(opts[:read]) read_pref = opts[:read] || read_preference selector = ServerSelector.get(read_pref || server_selector) with_session(opts) do |session| context = Operation::Context.new( client: client, session: session, operation_timeouts: operation_timeouts(opts) ) cmd = { count: collection.name } cmd[:maxTimeMS] = opts[:max_time_ms] if opts[:max_time_ms] cmd[:readConcern] = Options::Mapper.transform_values_to_strings(read_concern) if read_concern operation = Operation::Count.new( selector: cmd, db_name: database.name, read: read_pref, session: session, comment: opts[:comment] ) tracer.trace_operation(operation, context, op_name: 'estimatedDocumentCount') do read_with_retry(session, selector, context) do |server| result = operation.execute(server, context: context) result.n.to_i end rescue Error::OperationFailure::Family => e raise unless e.code == 26 # NamespaceNotFound # This should only happen with the aggregation pipeline path # (server 4.9+). Previous servers should return 0 for nonexistent # collections. 0 end end end |
#hint(hint = nil) ⇒ Hash, View
The index that MongoDB will be forced to use for the query.
398 399 400 |
# File 'lib/mongo/collection/view/readable.rb', line 398 def hint(hint = nil) configure(:hint, hint) end |
#limit(limit = nil) ⇒ Integer, View
The max number of docs to return from the query.
412 413 414 |
# File 'lib/mongo/collection/view/readable.rb', line 412 def limit(limit = nil) configure(:limit, limit) end |
#map_reduce(map, reduce, options = {}) ⇒ MapReduce
Execute a map/reduce operation on the collection view.
428 429 430 |
# File 'lib/mongo/collection/view/readable.rb', line 428 def map_reduce(map, reduce, = {}) MapReduce.new(self, map, reduce, @options.merge()) end |
#max_await_time_ms(max = nil) ⇒ Integer, View
A cumulative time limit in milliseconds for processing get more operations on a cursor.
637 638 639 |
# File 'lib/mongo/collection/view/readable.rb', line 637 def max_await_time_ms(max = nil) configure(:max_await_time_ms, max) end |
#max_scan(value = nil) ⇒ Integer, View
This option is deprecated as of MongoDB server version 4.0.
Set the max number of documents to scan.
445 446 447 |
# File 'lib/mongo/collection/view/readable.rb', line 445 def max_scan(value = nil) configure(:max_scan, value) end |
#max_time_ms(max = nil) ⇒ Integer, View
A cumulative time limit in milliseconds for processing operations on a cursor.
651 652 653 |
# File 'lib/mongo/collection/view/readable.rb', line 651 def max_time_ms(max = nil) configure(:max_time_ms, max) end |
#max_value(value = nil) ⇒ Hash, View
Set the maximum value to search.
459 460 461 |
# File 'lib/mongo/collection/view/readable.rb', line 459 def max_value(value = nil) configure(:max_value, value) end |
#min_value(value = nil) ⇒ Hash, View
Set the minimum value to search.
473 474 475 |
# File 'lib/mongo/collection/view/readable.rb', line 473 def min_value(value = nil) configure(:min_value, value) end |
#modifiers(doc = nil) ⇒ Hash, View
If called without arguments or with a nil argument, returns the legacy (OP_QUERY) server modifiers for the current view. If called with a non-nil argument, which must be a Hash or a subclass, merges the provided modifiers into the current view. Both string and symbol keys are allowed in the input hash.
618 619 620 621 622 623 624 |
# File 'lib/mongo/collection/view/readable.rb', line 618 def modifiers(doc = nil) if doc.nil? Operation::Find::Builder::Modifiers.map_server_modifiers() else new(.merge(Operation::Find::Builder::Modifiers.(BSON::Document.new(doc)))) end end |
#no_cursor_timeout ⇒ View
The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that.
486 487 488 |
# File 'lib/mongo/collection/view/readable.rb', line 486 def no_cursor_timeout configure(:no_cursor_timeout, true) end |
#parallel_scan(cursor_count, options = {}) ⇒ Object
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 |
# File 'lib/mongo/collection/view/readable.rb', line 707 def parallel_scan(cursor_count, = {}) session = if [:session] # The session would be overwritten by the one in +options+ later. client.get_session(@options) end server = server_selector.select_server(cluster, nil, session) spec = { coll_name: collection.name, db_name: database.name, cursor_count: cursor_count, read_concern: read_concern, session: session, }.update() session = spec[:session] op = Operation::ParallelScan.new(spec) # Note that the context object shouldn't be reused for subsequent # GetMore operations. context = Operation::Context.new(client: client, session: session) result = op.execute(server, context: context) result.cursor_ids.map do |cursor_id| spec = { cursor_id: cursor_id, coll_name: collection.name, db_name: database.name, session: session, batch_size: batch_size, # max_time_ms is not being passed here, I assume intentionally? } op = Operation::GetMore.new(spec) context = Operation::Context.new( client: client, session: session, connection_global_id: result.connection_global_id ) result = if server.load_balancer? # Connection will be checked in when cursor is drained. connection = server.pool.check_out(context: context) op.execute_with_connection(connection, context: context) else op.execute(server, context: context) end Cursor.new(self, result, server, session: session) end end |
#projection(document = nil) ⇒ Hash, View
A value of 0 excludes a field from the doc. A value of 1 includes it. Values must all be 0 or all be 1, with the exception of the _id value. The _id field is included by default. It must be excluded explicitly.
The fields to include or exclude from each doc in the result set.
504 505 506 507 |
# File 'lib/mongo/collection/view/readable.rb', line 504 def projection(document = nil) validate_doc!(document) if document configure(:projection, document) end |
#read(value = nil) ⇒ Symbol, View
If none is specified for the query, the read preference of the collection will be used.
The read preference to use for the query.
520 521 522 523 524 |
# File 'lib/mongo/collection/view/readable.rb', line 520 def read(value = nil) return read_preference if value.nil? configure(:read, value) end |
#read_concern ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
679 680 681 682 683 684 685 |
# File 'lib/mongo/collection/view/readable.rb', line 679 def read_concern if [:session] && [:session].in_transaction? [:session].send(:txn_read_concern) || collection.client.read_concern else collection.read_concern end end |
#read_preference ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 |
# File 'lib/mongo/collection/view/readable.rb', line 688 def read_preference @read_preference ||= begin # Operation read preference is always respected, and has the # highest priority. If we are in a transaction, we look at # transaction read preference and default to client, ignoring # collection read preference. If we are not in transaction we # look at collection read preference which defaults to client. rp = if [:read] [:read] elsif [:session] && [:session].in_transaction? [:session].txn_read_preference || collection.client.read_preference else collection.read_preference end Lint.validate_underscore_read_preference(rp) rp end end |
#return_key(value = nil) ⇒ true, ...
Set whether to return only the indexed field or fields.
536 537 538 |
# File 'lib/mongo/collection/view/readable.rb', line 536 def return_key(value = nil) configure(:return_key, value) end |
#show_disk_loc(value = nil) ⇒ true, ... Also known as: show_record_id
Set whether the disk location should be shown for each document.
551 552 553 |
# File 'lib/mongo/collection/view/readable.rb', line 551 def show_disk_loc(value = nil) configure(:show_disk_loc, value) end |
#skip(number = nil) ⇒ Integer, View
The number of docs to skip before returning results.
567 568 569 |
# File 'lib/mongo/collection/view/readable.rb', line 567 def skip(number = nil) configure(:skip, number) end |
#snapshot(value = nil) ⇒ Object
This option is deprecated as of MongoDB server version 4.0.
When set to true, prevents documents from returning more than once.
Set the snapshot value for the view.
585 586 587 |
# File 'lib/mongo/collection/view/readable.rb', line 585 def snapshot(value = nil) configure(:snapshot, value) end |
#sort(spec = nil) ⇒ Hash, View
The key and direction pairs by which the result set will be sorted.
600 601 602 |
# File 'lib/mongo/collection/view/readable.rb', line 600 def sort(spec = nil) configure(:sort, spec) end |
#timeout_ms(timeout_ms = nil) ⇒ Integer, View
The per-operation timeout in milliseconds. Must a positive integer.
674 675 676 |
# File 'lib/mongo/collection/view/readable.rb', line 674 def timeout_ms(timeout_ms = nil) configure(:timeout_ms, timeout_ms) end |