123456789_123456789_123456789_123456789_123456789_

Class: Mongo::Database::View

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, Forwardable
Instance Chain:
Inherits: Object
Defined in: lib/mongo/database/view.rb

Overview

A class representing a view of a database.

Since:

  • 2.0.0

Class Method Summary

Instance Attribute Summary

::Mongo::CursorHost - Included

#cursor

Returns the cursor associated with this view, if any.

#timeout_mode

Instance Method Summary

::Mongo::Cursor::NonTailable - Included

#cursor_type

These views are always non-tailable.

#timeout_mode

These views apply timeouts to each iteration of a cursor, as opposed to the entire lifetime of the cursor.

::Mongo::CursorHost - Included

#validate_timeout_mode!

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

::Mongo::Retryable - Included

#read_worker

Returns the read worker for handling retryable reads.

#select_server

This is a separate method to make it possible for the test suite to assert that server selection is performed during retry attempts.

#write_worker

Returns the write worker for handling retryable writes.

Constructor Details

.new(database, options = {}) ⇒ View

Create the new database view.

Examples:

Create the new database view.

Database::View.new(database)

Parameters:

  • database (Database)

    The database.

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

    The options to configure the view with.

Options Hash (options):

  • :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 database or the client.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 149

def initialize(database, options = {})
  @database = database
  @operation_timeout_ms = options.delete(:timeout_ms)

  validate_timeout_mode!(options)

  @batch_size =  nil
  @limit = nil
  @collection = @database[Database::COMMAND]
end

Instance Attribute Details

#batch_sizeInteger (readonly)

Returns:

  • (Integer)

    batch_size The size of the batch of results when sending the listCollections command.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 40

attr_reader :batch_size

#collectionCollection (readonly)

Returns:

  • (Collection)

    collection The command collection.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 46

attr_reader :collection

#database (readonly)

This method is for internal use only.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 161

attr_reader :database

#limitInteger (readonly)

Returns:

  • (Integer)

    limit The limit when sending a command.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 43

attr_reader :limit

#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/database/view.rb', line 167

attr_reader :operation_timeout_ms

Instance Method Details

#aggregate(pipeline, options = {}) ⇒ Collection::View::Aggregation

This method is for internal use only.

Execute an aggregation on the database view.

Examples:

Aggregate documents.

view.aggregate([
  { "$listLocalSessions" => {} }
])

Parameters:

  • pipeline (Array<Hash>)

    The aggregation pipeline.

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

    The aggregation options.

Returns:

Since:

  • 2.10.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 183

def aggregate(pipeline, options = {})
  Collection::View::Aggregation.new(self, pipeline, options)
end

#collection_names(options = {}) ⇒ Array<String>

Note:

The set of returned collection names depends on the version of MongoDB server that fulfills the request.

Get all the names of the non-system collections in the database.

See https://mongodb.com/docs/manual/reference/command/listCollections/
for more information and usage.

Parameters:

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

    ::Mongo::Options for the listCollections command.

Options Hash (options):

  • :batch_size (Integer)

    The batch size for results returned from the listCollections command.

  • :filter (Hash)

    A filter on the collections returned.

  • :authorized_collections (true, false)

    A flag, when set to true, that allows a user without the required privilege to run the command when access control is enforced.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :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 database or the client.

  • :session (Session)

    The session to use.

Returns:

  • (Array<String>)

    The names of all non-system collections.

Since:

  • 2.0.0

[ GitHub ]

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

def collection_names(options = {})
  @batch_size = options[:batch_size]
  session = client.get_session(options)
  context = Operation::Context.new(
    client: client,
    session: session,
    operation_timeouts: operation_timeouts(options)
  )
  cursor = read_with_retry_cursor(session, ServerSelector.primary, self, context: context) do |server|
    send_initial_query(server, session, context, options.merge(name_only: true))
  end
  cursor.map do |info|
    if cursor.initial_result.connection_description.features.list_collections_enabled?
      info['name']
    else
      (info['name'] &&
        info['name'].sub("#{@database.name}.", ''))
    end
  end.reject do |name|
    name.start_with?('system.') || name.include?('$')
  end
end

#collections_info(session, server_selector, options = {}, &block) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 210

def collections_info(session, server_selector, options = {}, &block)
  description = nil
  context = Operation::Context.new(
    client: client,
    session: session,
    operation_timeouts: operation_timeouts(options)
  )
  cursor = read_with_retry_cursor(session, server_selector, self, context: context) do |server|
    # TODO take description from the connection used to send the query
    # once https://jira.mongodb.org/browse/RUBY-1601 is fixed.
    description = server.description
    send_initial_query(server, session, context, options)
  end
  # On 3.0+ servers, we get just the collection names.
  # On 2.6 server, we get collection names prefixed with the database
  # name. We need to filter system collections out here because
  # in the caller we don't know which server version executed the
  # command and thus what the proper filtering logic should be
  # (it is valid for collection names to have dots, thus filtering out
  # collections named system.* here for 2.6 servers would actually
  # filter out collections in the system database).
  if description.server_version_gte?('3.0')
    cursor.reject do |doc|
      doc['name'].start_with?('system.') || doc['name'].include?('$')
    end
  else
    cursor.reject do |doc|
      doc['name'].start_with?("#{database.name}.system") || doc['name'].include?('$')
    end
  end
end

#collections_info_spec(session, options = {}) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 242

def collections_info_spec(session, options = {})
  { selector: {
      listCollections: 1,
      cursor: batch_size ? { batchSize: batch_size } : {} },
    db_name: @database.name,
    session: session
  }.tap do |spec|
    spec[:selector][:nameOnly] = true if options[:name_only]
    spec[:selector][:filter] = options[:filter] if options[:filter]
    spec[:selector][:authorizedCollections] = true if options[:authorized_collections]
    spec[:comment] = options[:comment] if options[:comment]
  end
end

#initial_query_op(session, options = {}) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 256

def initial_query_op(session, options = {})
  Operation::CollectionsInfo.new(collections_info_spec(session, options))
end

#list_collections(options = {}) ⇒ Array<Hash>

Note:

The set of collections returned, and the schema of the information hash per collection, depends on the MongoDB server version that fulfills the request.

Get info on all the collections in the database.

Examples:

Get info on each collection.

database.list_collections

Parameters:

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

Options Hash (options):

  • :filter (Hash)

    A filter on the collections returned.

  • :name_only (true, false)

    Indicates whether command should return just collection/view names and type or return both the name and other information

  • :authorized_collections (true, false)

    A flag, when set to true and used with nameOnly: true, that allows a user without the required privilege to run the command when access control is enforced

    See mongodb.com/docs/manual/reference/command/listCollections/ for more information and usage.

  • :session (Session)

    The session to use.

  • :deserialize_as_bson (Boolean)

    Whether to deserialize this message using BSON types instead of native Ruby types wherever possible.

Returns:

  • (Array<Hash>)

    Info for each collection in the database.

Since:

  • 2.0.5

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 127

def list_collections(options = {})
  session = client.get_session(options)
  collections_info(session, ServerSelector.primary, 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).

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 198

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

#send_initial_query(server, session, context, options = {}) ⇒ Operation::Result (private)

Sends command that obtains information about the database.

This command returns a cursor, so there could be additional commands, therefore this method is called send initial command.

Parameters:

Options Hash (options):

  • :filter (Hash | nil)

    A query expression to filter the list of collections.

  • :name_only (true | false | nil)

    A flag to indicate whether the command should return just the collection/view names and type or return both the name and other information.

  • :authorized_collections (true | false | nil)

    A flag, when set to true and used with name_only: true, that allows a user without the required privilege (i.e. listCollections action on the database) to run the command when access control is enforced.

  • :comment (Object | nil)

    A user-provided comment to attach to this command.

  • :deserialize_as_bson (true | false | nil)

    Whether the query results should be deserialized to BSON types, or to Ruby types (where possible).

Returns:

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 285

def send_initial_query(server, session, context, options = {})
  opts = options.dup
  execution_opts = {}
  if opts.key?(:deserialize_as_bson)
    execution_opts[:deserialize_as_bson] = opts.delete(:deserialize_as_bson)
  end
  if server.load_balancer?
    connection = server.pool.check_out(context: context)
    initial_query_op(session, opts).execute_with_connection(
      connection,
      context: context,
      options: execution_opts
    )
  else
    initial_query_op(session, opts).execute(
      server,
      context: context,
      options: execution_opts
    )
  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 database.

Returns:

  • (Integer | nil)

    the timeout_ms for this operation

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/database/view.rb', line 191

def timeout_ms
  operation_timeout_ms || database.timeout_ms
end