123456789_123456789_123456789_123456789_123456789_

Class: Mongo::Collection::View

Overview

Note:

The View API is semipublic.

Representation of a query and options producing a result set of documents.

A View can be modified using helpers. Helpers can be chained, as each one returns a View if arguments are provided.

The query message is sent to the server when a “terminator” is called. For example, when #each is called on a View, a ::Mongo::Cursor object is created, which then sends the query to the server.

A View is not created directly by a user. Rather, View creates a View when a CRUD operation is called and returns it to the user to interact with.

Since:

  • 2.0.0

Constant Summary

Explainable - Included

ALL_PLANS_EXECUTION, EXECUTION_STATS, QUERY_PLANNER

Writable - Included

ARRAY_FILTERS

Class Method Summary

Instance Attribute Summary

Explainable - Included

Iterable - Included

#prefer_cached_cursor?

If the caching cursor is closed and was not fully iterated, the documents we have in it are not the complete result set and we have no way of completing that iteration.

#use_query_cache?

::Mongo::CursorHost - Included

#cursor

Returns the cursor associated with this view, if any.

#timeout_mode

Immutable - Included

Instance Method Summary

Writable - Included

#delete_many

Remove documents from the collection.

#delete_one

Remove a document from the collection.

#find_one_and_delete

Finds a single document in the database via findAndModify and deletes it, returning the original document.

#find_one_and_replace

Finds a single document and replaces it.

#find_one_and_update

Finds a single document and updates it.

#replace_one

Replaces a single document in the database with the new document.

#update_many

Update documents in the collection.

#update_one

Update a single document in the collection.

#validate_replacement_documents!

Check the replacement documents to make sure they don’t have atomic modifiers.

#validate_update_documents!

Checks the update documents to make sure they only have atomic modifiers.

Explainable - Included

#explain

Get the query plan for the query.

#explain_options

Readable - Included

#aggregate

Execute an aggregation on the collection view.

#allow_disk_use

Allows the server to write temporary data to disk while executing a find operation.

#allow_partial_results

Allows the query to get partial results if some shards are down.

#await_data

Tell the query’s cursor to stay open and wait for data.

#batch_size

The number of documents returned in each batch of results from MongoDB.

#comment

Associate a comment with the query.

#count

Get a count of matching documents in the collection.

#count_documents

Get a count of matching documents in the collection.

#cursor_type

The type of cursor to use.

#distinct

Get a list of distinct values for a specific field.

#estimated_document_count

Gets an estimate of the count of documents in a collection using collection metadata.

#hint

The index that MongoDB will be forced to use for the query.

#limit

The max number of docs to return from the query.

#map_reduce

Execute a map/reduce operation on the collection view.

#max_await_time_ms

A cumulative time limit in milliseconds for processing get more operations on a cursor.

#max_scan

Set the max number of documents to scan.

#max_time_ms

A cumulative time limit in milliseconds for processing operations on a cursor.

#max_value

Set the maximum value to search.

#min_value

Set the minimum value to search.

#modifiers

If called without arguments or with a nil argument, returns the legacy (OP_QUERY) server modifiers for the current view.

#no_cursor_timeout

The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use.

#parallel_scan,
#projection

The fields to include or exclude from each doc in the result set.

#read

The read preference to use for the query.

#read_concern, #read_preference,
#return_key

Set whether to return only the indexed field or fields.

#show_disk_loc

Set whether the disk location should be shown for each document.

#show_record_id
#skip

The number of docs to skip before returning results.

#snapshot

Set the snapshot value for the view.

#sort

The key and direction pairs by which the result set will be sorted.

#timeout_ms

The per-operation timeout in milliseconds.

#collation, #server_selector, #validate_doc!

Iterable - Included

#close_query

Cleans up resources associated with this query.

#each

Iterate through documents returned by a query with this View.

#kill_cursors
#cache_options, #cached_cursor, #compute_limit_for_cached_query, #initial_query_op,
#maybe_set_tailable_options

Add tailable cusror options to the command specifiction if needed.

#new_cursor_for_iteration

Start a new cursor for use when iterating (via #each).

#oplog_replay, #select_cursor, #send_initial_query

::Mongo::CursorHost - Included

#validate_timeout_mode!

Ensure the timeout mode is appropriate for other options that have been given.

Immutable - Included

Constructor Details

.new(collection, filter = {}, options = {}) ⇒ View

Creates a new View.

Examples:

Find all users named Emily.

View.new(collection, {:name => 'Emily'})

Find all users named Emily skipping 5 and returning 10.

View.new(collection, {:name => 'Emily'}, :skip => 5, :limit => 10)

Find all users named Emily using a specific read preference.

View.new(collection, {:name => 'Emily'}, :read => :secondary_preferred)

Parameters:

  • collection (Collection)

    The ::Mongo::Collection to query.

  • filter (Hash) (defaults to: {})

    The query filter.

  • options (Hash) (defaults to: {})

    The additional query options.

Options Hash (options):

  • :allow_disk_use (true, false)

    When set to true, the server can write temporary data to disk while executing the find operation. This option is only available on MongoDB server versions 4.4 and newer.

  • :batch_size (Integer)

    The number of documents to return in each response from MongoDB.

  • :collation (Hash)

    The collation to use.

  • :comment (String)

    Associate a comment with the query.

  • :cursor_type (:tailable, :tailable_await)

    The type of cursor to use.

  • :explain (Hash)

    Execute an explain with the provided explain options (known options are :verbose and :verbosity) rather than a find.

  • :hint (Hash)

    Override the default index selection and force MongoDB to use a specific index for the query.

  • :limit (Integer)

    Max number of documents to return.

  • :max_scan (Integer)

    Constrain the query to only scan the specified number of documents. Use to prevent queries from running for too long. Deprecated as of MongoDB server version 4.0.

  • :projection (Hash)

    The fields to include or exclude in the returned documents.

  • :read (Hash)

    The read preference to use for the query. If none is provided, the collection’s default read preference is used.

  • :read_concern (Hash)

    The read concern to use for the query.

  • :show_disk_loc (true | false)

    Return disk location info as a field in each doc.

  • :skip (Integer)

    The number of documents to skip.

  • :snapshot (true | false)

    Prevents returning a document more than once. Deprecated as of MongoDB server version 4.0.

  • :sort (Hash)

    The key and direction pairs used to sort the results.

  • :timeout_mode (:cursor_lifetime | :iteration)

    How to interpret :timeout_ms (whether it applies to the lifetime of the cursor, or per iteration).

  • :timeout_ms (Integer)

    The operation timeout in milliseconds. Must be a non-negative integer. An explicit value of 0 means infinite. The default value is unset which means the value is inherited from the collection or the database or the client.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 169

def initialize(collection, filter = {}, options = {})
  validate_doc!(filter)

  filter = BSON::Document.new(filter)
  options = BSON::Document.new(options)

  @collection = collection
  @operation_timeout_ms = options.delete(:timeout_ms)

  validate_timeout_mode!(options)

  # This is when users pass $query in filter and other modifiers
  # alongside?
  query = filter.delete(:$query)
  # This makes modifiers contain the filter if filter wasn't
  # given via $query but as top-level keys, presumably
  # downstream code ignores non-modifier keys in the modifiers?
  modifiers = filter.merge(options.delete(:modifiers) || {})
  @filter = (query || filter).freeze
  @options = Operation::Find::Builder::Modifiers.map_driver_options(modifiers).merge!(options).freeze
end

Instance Attribute Details

#collectionCollection (readonly)

Returns:

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 56

attr_reader :collection

#filterHash (readonly) Also known as: #selector

Returns:

  • (Hash)

    The query filter.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 59

attr_reader :filter

#operation_timeout_msInteger | nil | The timeout_ms value that was passed as an option to the view. (readonly)

This method is for internal use only.

Returns:

  • (Integer | nil | The timeout_ms value that was passed as an option to the view.)

    Integer | nil | The timeout_ms value that was passed as an option to the view.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 81

attr_reader :operation_timeout_ms

#selector (readonly)

Alias for #filter.

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 75

alias :selector :filter

Instance Method Details

#==(other) ⇒ true, false Also known as: #eql?

Compare two View objects.

Examples:

Compare the view with another object.

view == other

Returns:

  • (true, false)

    Equal if collection, filter, and options of two View match.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 92

def ==(other)
  return false unless other.is_a?(View)
  collection == other.collection &&
      filter == other.filter &&
      options == other.options
end

#eql?(other)

Alias for #==.

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 98

alias_method :eql?, :==

#hashInteger

A hash value for the View composed of the collection namespace, hash of the options and hash of the filter.

Examples:

Get the hash value.

view.hash

Returns:

  • (Integer)

    A hash value of the View object.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 109

def hash
  [ collection.namespace, options.hash, filter.hash ].hash
end

#initialize_copy(other) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 240

def initialize_copy(other)
  @collection = other.collection
  @options = other.options.dup
  @filter = other.filter.dup
end

#inspectString

Get a human-readable string representation of View.

Examples:

Get the inspection.

view.inspect

Returns:

  • (String)

    A string representation of a View instance.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 207

def inspect
  "#<Mongo::Collection::View:0x#{object_id} namespace='#{collection.namespace}'" +
      " @filter=#{filter.to_s} @options=#{options.to_s}>"
end

#new(options) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 246

def new(options)
  options = options.merge(timeout_ms: operation_timeout_ms) if operation_timeout_ms
  View.new(collection, filter, options)
end

#operation_timeouts(opts = {}) ⇒ Hash

This method is for internal use only.

Returns:

  • (Hash)

    timeout_ms value set on the operation level (if any), and/or timeout_ms that is set on collection/database/client level (if any).

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 228

def operation_timeouts(opts = {})
  {}.tap do |result|
    if opts[:timeout_ms] || operation_timeout_ms
      result[:operation_timeout_ms] = opts[:timeout_ms] || operation_timeout_ms
    else
      result[:inherited_timeout_ms] = collection.timeout_ms
    end
  end
end

#timeout_msInteger | nil

The timeout_ms value to use for this operation; either specified as an option to the view, or inherited from the collection.

Returns:

  • (Integer | nil)

    the timeout_ms for this operation

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 195

def timeout_ms
  operation_timeout_ms || collection.timeout_ms
end

#view (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 251

def view; self; end

#with_session(opts = {}, &block) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 253

def with_session(opts = {}, &block)
  client.with_session(@options.merge(opts), &block)
end

#write_concernMongo::WriteConcern

Get the write concern on this View.

Examples:

Get the write concern.

view.write_concern

Returns:

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/collection/view.rb', line 220

def write_concern
  WriteConcern.get(options[:write_concern] || options[:write] || collection.write_concern)
end