Class: Mongo::Collection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Helpers, QueryableEncryption, Retryable
Defined in:
lib/mongo/collection.rb,
lib/mongo/collection/view.rb,
lib/mongo/collection/helpers.rb,
lib/mongo/collection/view/iterable.rb,
lib/mongo/collection/view/readable.rb,
lib/mongo/collection/view/writable.rb,
lib/mongo/collection/view/immutable.rb,
lib/mongo/collection/view/map_reduce.rb,
lib/mongo/collection/view/aggregation.rb,
lib/mongo/collection/view/explainable.rb,
lib/mongo/collection/view/change_stream.rb,
lib/mongo/collection/queryable_encryption.rb,
lib/mongo/collection/view/builder/map_reduce.rb,
lib/mongo/collection/view/builder/aggregation.rb,
lib/mongo/collection/view/aggregation/behavior.rb,
lib/mongo/collection/view/change_stream/retryable.rb

Overview

Represents a collection in the database and operations that can directly be applied to one.

Since:

  • 2.0.0

Defined Under Namespace

Modules: Helpers, QueryableEncryption Classes: View

Constant Summary collapse

CAPPED =

The capped option.

Since:

  • 2.1.0

'capped'.freeze
NS =

The ns field constant.

Since:

  • 2.1.0

'ns'.freeze
CHANGEABLE_OPTIONS =

Options that can be updated on a new Collection instance via the #with method.

Since:

  • 2.1.0

[ :read, :read_concern, :write, :write_concern ].freeze
CREATE_COLLECTION_OPTIONS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Options map to transform create collection options.

Since:

  • 2.0.0

{
  :time_series => :timeseries,
  :expire_after => :expireAfterSeconds,
  :clustered_index => :clusteredIndex,
  :change_stream_pre_and_post_images => :changeStreamPreAndPostImages,
  :encrypted_fields => :encryptedFields,
  :validator => :validator,
  :view_on => :viewOn
}

Constants included from QueryableEncryption

QueryableEncryption::QE2_MIN_WIRE_VERSION

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#do_drop

Methods included from QueryableEncryption

#maybe_create_qe_collections, #maybe_drop_emm_collections

Methods included from Retryable

#read_worker, #select_server, #write_worker

Constructor Details

#initialize(database, name, options = {}) ⇒ Collection

Instantiate a new collection.

Examples:

Instantiate a new collection.

Mongo::Collection.new(database, 'test')

Parameters:

  • database (Mongo::Database)

    The collection’s database.

  • name (String, Symbol)

    The collection name.

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

    The collection options.

  • opts (Hash)

    a customizable set of options

Options Hash (options):

  • :read_concern (Hash)

    The read concern options hash, with the following optional keys:

    • :level – the read preference level as a symbol; valid values

      are *:local*, *:majority*, and *:snapshot*
      
  • :read (Hash)

    The read preference options. The hash may have the following items:

    • :mode – read preference specified as a symbol; valid values are :primary, :primary_preferred, :secondary, :secondary_preferred and :nearest.

    • :tag_sets – an array of hashes.

    • :local_threshold.

  • :session (Session)

    The session to use for the operation.

  • :size (Integer)

    The size of the capped collection.

  • :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.

Raises:

Since:

  • 2.0.0



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/mongo/collection.rb', line 162

def initialize(database, name, options = {})
  raise Error::InvalidCollectionName.new unless name
  if options[:write] && options[:write_concern] && options[:write] != options[:write_concern]
    raise ArgumentError, "If :write and :write_concern are both given, they must be identical: #{options.inspect}"
  end
  @database = database
  @name = name.to_s.freeze
  @options = options.dup
  @timeout_ms = options.delete(:timeout_ms)
=begin WriteConcern object support
  if @options[:write_concern].is_a?(WriteConcern::Base)
    # Cache the instance so that we do not needlessly reconstruct it.
    @write_concern = @options[:write_concern]
    @options[:write_concern] = @write_concern.options
  end
=end
  @options.freeze
end

Instance Attribute Details

#databaseMongo::Database (readonly)

Returns The database the collection resides in.

Returns:

Since:

  • 2.0.0



46
47
48
# File 'lib/mongo/collection.rb', line 46

def database
  @database
end

#nameString (readonly)

Returns The name of the collection.

Returns:

  • (String)

    The name of the collection.

Since:

  • 2.0.0



49
50
51
# File 'lib/mongo/collection.rb', line 49

def name
  @name
end

#optionsHash (readonly)

Returns The collection options.

Returns:

  • (Hash)

    The collection options.

Since:

  • 2.0.0



52
53
54
# File 'lib/mongo/collection.rb', line 52

def options
  @options
end

Instance Method Details

#==(other) ⇒ true | false

Check if a collection is equal to another object. Will check the name and the database for equality.

Examples:

Check collection equality.

collection == other

Parameters:

  • other (Object)

    The object to check.

Returns:

  • (true | false)

    If the objects are equal.

Since:

  • 2.0.0



89
90
91
92
# File 'lib/mongo/collection.rb', line 89

def ==(other)
  return false unless other.is_a?(Collection)
  name == other.name && database == other.database && options == other.options
end

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

Perform an aggregation on the collection.

Examples:

Perform an aggregation.

collection.aggregate([ { "$group" => { "_id" => "$city", "tpop" => { "$sum" => "$pop" }}} ])

Parameters:

  • pipeline (Array<Hash>)

    The aggregation pipeline.

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

    The aggregation options.

Options Hash (options):

  • :allow_disk_use (true | false)

    Set to true if disk usage is allowed during the aggregation.

  • :batch_size (Integer)

    The number of documents to return per batch.

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :hint (String)

    The index to use for the aggregation.

  • :let (Hash)

    Mapping of variables to use in the pipeline. See the server documentation for details.

  • :max_time_ms (Integer)

    The maximum amount of time to allow the query to run, in milliseconds. This option is deprecated, use :timeout_ms instead.

  • :session (Session)

    The session to use.

  • :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.

Returns:

Since:

  • 2.1.0



568
569
570
# File 'lib/mongo/collection.rb', line 568

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

#bulk_write(requests, options = {}) ⇒ BulkWrite::Result

Execute a batch of bulk write operations.

Examples:

Execute a bulk write.

collection.bulk_write(operations, options)

Parameters:

  • requests (Enumerable<Hash>)

    The bulk write requests.

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

    The options.

Options Hash (options):

  • :ordered (true | false)

    Whether the operations should be executed in order.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer, :fsync => Boolean, :j => Boolean.

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :session (Session)

    The session to use for the set of operations.

  • :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.

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

Returns:

Since:

  • 2.0.0



942
943
944
# File 'lib/mongo/collection.rb', line 942

def bulk_write(requests, options = {})
  BulkWrite.new(self, requests, options).execute
end

#capped?true | false

Is the collection capped?

Examples:

Is the collection capped?

collection.capped?

Returns:

  • (true | false)

    If the collection is capped.

Since:

  • 2.0.0



321
322
323
324
325
# File 'lib/mongo/collection.rb', line 321

def capped?
  database.list_collections(filter: { name: name })
    .first
    &.dig('options', CAPPED) || false
end

#count(filter = nil, options = {}) ⇒ Integer

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 (only works on 3.6+)
* $near should be replaced with $geoWithin with $center
* $nearSphere should be replaced with $geoWithin with $centerSphere

Gets an estimated number of matching documents in the collection.

Examples:

Get the count.

collection.count(name: 1)

Parameters:

  • filter (Hash) (defaults to: nil)

    A filter for matching documents.

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

    The count options.

Options Hash (options):

  • :hint (Hash)

    The index to use.

  • :limit (Integer)

    The maximum number of documents to count.

  • :max_time_ms (Integer)

    The maximum amount of time to allow the query to run, in milliseconds. This option is deprecated, use :timeout_ms instead.

  • :skip (Integer)

    The number of documents to skip before counting.

  • :read (Hash)

    The read preference options.

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

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

Returns:

  • (Integer)

    The document count.

Since:

  • 2.1.0



685
686
687
# File 'lib/mongo/collection.rb', line 685

def count(filter = nil, options = {})
  View.new(self, filter || {}, options).count(options)
end

#count_documents(filter = {}, options = {}) ⇒ Integer

Gets the number of documents matching the query. Unlike the deprecated #count method, this will return the exact number of documents matching the filter (or exact number of documents in the collection, if no filter is provided) rather than an estimate.

Use #estimated_document_count to retrieve an estimate of the number of documents in the collection using the collection metadata.

Parameters:

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

    A filter for matching documents.

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

    Options for the operation.

Options Hash (options):

  • :skip (Integer)

    The number of documents to skip.

  • :hint (Hash)

    Override default index selection and force MongoDB to use a specific index for the query. Requires server version 3.6+.

  • :limit (Integer)

    Max number of docs to count.

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run.

  • :read (Hash)

    The read preference options.

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

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

Returns:

  • (Integer)

    The document count.

Since:

  • 2.6.0



719
720
721
# File 'lib/mongo/collection.rb', line 719

def count_documents(filter = {}, options = {})
  View.new(self, filter, options).count_documents(options)
end

#create(opts = {}) ⇒ Result

Force the collection to be created in the database.

Examples:

Force the collection to be created.

collection.create

Parameters:

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

    The options for the create operation.

Options Hash (opts):

  • :capped (true | false)

    Create a fixed-sized collection.

  • :change_stream_pre_and_post_images (Hash)

    Used to enable pre- and post-images on the created collection. The hash may have the following items:

    • :enabled – true or false.

  • :clustered_index (Hash)

    Create a clustered index. This option specifies how this collection should be clustered on _id. The hash may have the following items:

    • :key – The clustered index key field. Must be set to { _id: 1 }.

    • :unique – Must be set to true. The collection will not accept inserted or updated documents where the clustered index key value matches an existing value in the index.

    • :name – Optional. A name that uniquely identifies the clustered index.

  • :collation (Hash)

    The collation to use when creating the collection. This option will not be sent to the server when calling collection methods.

  • :encrypted_fields (Hash)

    Hash describing encrypted fields for queryable encryption.

  • :expire_after (Integer)

    Number indicating after how many seconds old time-series data should be deleted.

  • :max (Integer)

    The maximum number of documents in a capped collection. The size limit takes precedents over max.

  • :pipeline (Array<Hash>)

    An array of pipeline stages. A view will be created by applying this pipeline to the view_on collection or view.

  • :session (Session)

    The session to use for the operation.

  • :size (Integer)

    The size of the capped collection.

  • :time_series (Hash)

    Create a time-series collection. The hash may have the following items:

    • :timeField – The name of the field which contains the date in each time series document.

    • :metaField – The name of the field which contains metadata in each time series document.

    • :granularity – Set the granularity to the value that is the closest match to the time span between consecutive incoming measurements. Possible values are “seconds” (default), “minutes”, and “hours”.

  • :validator (Hash)

    Hash describing document validation options for the collection.

  • :view_on (String)

    The name of the source collection or view from which to create a view.

  • :write (Hash)

    Deprecated. Equivalent to :write_concern option.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer|String, :fsync => Boolean, :j => Boolean.

Returns:

  • (Result)

    The result of the command.

Since:

  • 2.0.0



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/mongo/collection.rb', line 382

def create(opts = {})
  # Passing read options to create command causes it to break.
  # Filter the read options out. Session is also excluded here as it gets
  # used by the call to with_session and should not be part of the
  # operation. If it gets passed to the operation it would fail BSON
  # serialization.
  # TODO put the list of read options in a class-level constant when
  # we figure out what the full set of them is.
  options = Hash[self.options.merge(opts).reject do |key, value|
    %w(read read_preference read_concern session).include?(key.to_s)
  end]
  # Converting Ruby options to server style.
  CREATE_COLLECTION_OPTIONS.each do |ruby_key, server_key|
    if options.key?(ruby_key)
      options[server_key] = options.delete(ruby_key)
    end
  end
  operation = { :create => name }.merge(options)
  operation.delete(:write)
  operation.delete(:write_concern)
  client.send(:with_session, opts) do |session|
    write_concern = if opts[:write_concern]
      WriteConcern.get(opts[:write_concern])
    else
      self.write_concern
    end

    context = Operation::Context.new(
      client: client,
      session: session
    )
    maybe_create_qe_collections(opts[:encrypted_fields], client, session) do |encrypted_fields|
      Operation::Create.new(
        selector: operation,
        db_name: database.name,
        write_concern: write_concern,
        session: session,
        # Note that these are collection options, collation isn't
        # taken from options passed to the create method.
        collation: options[:collation] || options['collation'],
        encrypted_fields: encrypted_fields,
        validator: options[:validator],
      ).execute(
        next_primary(nil, session),
        context: context
      )
    end
  end
end

#delete_many(filter = nil, options = {}) ⇒ Result

Remove documents from the collection.

Examples:

Remove multiple documents from the collection.

collection.delete_many

Parameters:

  • filter (Hash) (defaults to: nil)

    The filter to use.

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

    The options.

Options Hash (options):

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :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.

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



994
995
996
# File 'lib/mongo/collection.rb', line 994

def delete_many(filter = nil, options = {})
  find(filter, options).delete_many(options)
end

#delete_one(filter = nil, options = {}) ⇒ Result

Remove a document from the collection.

Examples:

Remove a single document from the collection.

collection.delete_one

Parameters:

  • filter (Hash) (defaults to: nil)

    The filter to use.

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

    The options.

Options Hash (options):

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :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.

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



968
969
970
# File 'lib/mongo/collection.rb', line 968

def delete_one(filter = nil, options = {})
  find(filter, options).delete_one(options)
end

#distinct(field_name, filter = nil, options = {}) ⇒ Array<Object>

Get a list of distinct values for a specific field.

Examples:

Get the distinct values.

collection.distinct('name')

Parameters:

  • field_name (Symbol, String)

    The name of the field.

  • filter (Hash) (defaults to: nil)

    The documents from which to retrieve the distinct values.

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

    The distinct command options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the query to run, in milliseconds. This option is deprecated, use :timeout_ms instead.

  • :read (Hash)

    The read preference options.

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

  • :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.

Returns:

  • (Array<Object>)

    The list of distinct values.

Since:

  • 2.1.0



771
772
773
# File 'lib/mongo/collection.rb', line 771

def distinct(field_name, filter = nil, options = {})
  View.new(self, filter || {}, options).distinct(field_name, options)
end

#drop(opts = {}) ⇒ Result

Note:

An error returned if the collection doesn’t exist is suppressed.

Drop the collection. Will also drop all indexes associated with the collection, as well as associated queryable encryption collections.

Examples:

Drop the collection.

collection.drop

Parameters:

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

    The options for the drop operation.

  • options (Hash)

    a customizable set of options

Options Hash (opts):

  • :session (Session)

    The session to use for the operation.

  • :write_concern (Hash)

    The write concern options.

  • :encrypted_fields (Hash | nil)

    Encrypted fields hash that was provided to ‘create` collection helper.

Returns:

  • (Result)

    The result of the command.

Since:

  • 2.0.0



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/mongo/collection.rb', line 454

def drop(opts = {})
  client.with_session(opts) do |session|
    maybe_drop_emm_collections(opts[:encrypted_fields], client, session) do
      temp_write_concern = write_concern
      write_concern = if opts[:write_concern]
        WriteConcern.get(opts[:write_concern])
      else
        temp_write_concern
      end
      context = Operation::Context.new(
        client: client,
        session: session,
        operation_timeouts: operation_timeouts(opts)
      )
      operation = Operation::Drop.new({
        selector: { :drop => name },
        db_name: database.name,
        write_concern: write_concern,
        session: session,
      })
      do_drop(operation, session, context)
    end
  end
end

#estimated_document_count(options = {}) ⇒ Integer

Gets an estimate of the number of documents in the collection using the collection metadata.

Use #count_documents to retrieve the exact number of documents in the collection, or to count documents matching a filter.

Parameters:

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

    Options for the operation.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run for on the server.

  • :read (Hash)

    The read preference options.

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

Returns:

  • (Integer)

    The document count.

Since:

  • 2.6.0



744
745
746
# File 'lib/mongo/collection.rb', line 744

def estimated_document_count(options = {})
  View.new(self, {}, options).estimated_document_count(options)
end

#find(filter = nil, options = {}) ⇒ CollectionView

Find documents in the collection.

Examples:

Find documents in the collection by a selector.

collection.find(name: 1)

Get all documents in a collection.

collection.find

Parameters:

  • filter (Hash) (defaults to: nil)

    The filter to use in the find.

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

    The options for the find.

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.

  • :allow_partial_results (true | false)

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

  • :batch_size (Integer)

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

  • :collation (Hash)

    The collation to use.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :cursor_type (:tailable, :tailable_await)

    The type of cursor to use.

  • :limit (Integer)

    The max number of docs to return from the query.

  • :max_time_ms (Integer)

    The maximum amount of time to allow the query to run, in milliseconds. This option is deprecated, use :timeout_ms instead.

  • :modifiers (Hash)

    A document containing meta-operators modifying the output or behavior of a query.

  • :no_cursor_timeout (true | false)

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

  • :oplog_replay (true | false)

    For internal replication use only, applications should not set this option.

  • :projection (Hash)

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

  • :session (Session)

    The session to use.

  • :skip (Integer)

    The number of docs to skip before returning results.

  • :sort (Hash)

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

  • :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.

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

Returns:

  • (CollectionView)

    The collection view.

Since:

  • 2.0.0



532
533
534
# File 'lib/mongo/collection.rb', line 532

def find(filter = nil, options = {})
  View.new(self, filter || {}, options)
end

#find_one_and_delete(filter, options = {}) ⇒ BSON::Document?

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

Examples:

Find one document and delete it.

collection.find_one_and_delete(name: 'test')

Parameters:

  • filter (Hash)

    The filter to use.

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

    The options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the query to run, in milliseconds. This option is deprecated, use :timeout_ms instead.

  • :projection (Hash)

    The fields to include or exclude in the returned doc.

  • :sort (Hash)

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

  • :write_concern (Hash)

    The write concern options. Defaults to the collection’s write concern.

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

  • :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.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

Returns:

  • (BSON::Document, nil)

    The document, if found.

Since:

  • 2.1.0



1157
1158
1159
# File 'lib/mongo/collection.rb', line 1157

def find_one_and_delete(filter, options = {})
  find(filter, options).find_one_and_delete(options)
end

#find_one_and_replace(filter, replacement, options = {}) ⇒ BSON::Document

Finds a single document and replaces it, returning the original doc unless otherwise specified.

Examples:

Find a document and replace it, returning the original.

collection.find_one_and_replace({ name: 'test' }, { name: 'test1' })

Find a document and replace it, returning the new document.

collection.find_one_and_replace({ name: 'test' }, { name: 'test1' }, :return_document => :after)

Parameters:

  • filter (Hash)

    The filter to use.

  • replacement (BSON::Document)

    The replacement document.

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

    The options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run in milliseconds.

  • :projection (Hash)

    The fields to include or exclude in the returned doc.

  • :sort (Hash)

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

  • :return_document (Symbol)

    Either :before or :after.

  • :upsert (true | false)

    Whether to upsert if the document doesn’t exist.

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :write_concern (Hash)

    The write concern options. Defaults to the collection’s write concern.

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :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.

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



1243
1244
1245
# File 'lib/mongo/collection.rb', line 1243

def find_one_and_replace(filter, replacement, options = {})
  find(filter, options).find_one_and_update(replacement, options)
end

#find_one_and_update(filter, update, options = {}) ⇒ BSON::Document

Finds a single document via findAndModify and updates it, returning the original doc unless otherwise specified.

Examples:

Find a document and update it, returning the original.

collection.find_one_and_update({ name: 'test' }, { "$set" => { name: 'test1' }})

Find a document and update it, returning the updated document.

collection.find_one_and_update({ name: 'test' }, { "$set" => { name: 'test1' }}, :return_document => :after)

Parameters:

  • filter (Hash)

    The filter to use.

  • update (Hash | Array<Hash>)

    The update document or pipeline.

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

    The options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run in milliseconds.

  • :projection (Hash)

    The fields to include or exclude in the returned doc.

  • :sort (Hash)

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

  • :return_document (Symbol)

    Either :before or :after.

  • :upsert (true | false)

    Whether to upsert if the document doesn’t exist.

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :write_concern (Hash)

    The write concern options. Defaults to the collection’s write concern.

  • :collation (Hash)

    The collation to use.

  • :array_filters (Array)

    A set of filters specifying to which array elements an update should apply.

  • :session (Session)

    The session to use.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

  • :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.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



1201
1202
1203
# File 'lib/mongo/collection.rb', line 1201

def find_one_and_update(filter, update, options = {})
  find(filter, options).find_one_and_update(update, options)
end

#indexes(options = {}) ⇒ Index::View

Get a view of all indexes for this collection. Can be iterated or has more operations.

Examples:

Get the index view.

collection.indexes

Parameters:

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

    Options for getting a list of all indexes.

Options Hash (options):

  • :session (Session)

    The session to use.

Returns:

Since:

  • 2.0.0



788
789
790
# File 'lib/mongo/collection.rb', line 788

def indexes(options = {})
  Index::View.new(self, options)
end

#insert_many(documents, options = {}) ⇒ Result

Insert the provided documents into the collection.

Examples:

Insert documents into the collection.

collection.insert_many([{ name: 'test' }])

Parameters:

  • documents (Enumerable<Hash>)

    The documents to insert.

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

    The insert options.

Options Hash (options):

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :ordered (true | false)

    Whether the operations should be executed in order.

  • :session (Session)

    The session to use for the operation.

  • :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.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer, :fsync => Boolean, :j => Boolean.

Returns:

  • (Result)

    The database response wrapper.

Since:

  • 2.0.0



910
911
912
913
914
915
# File 'lib/mongo/collection.rb', line 910

def insert_many(documents, options = {})
  QueryCache.clear_namespace(namespace)

  inserts = documents.map{ |doc| { :insert_one => doc }}
  bulk_write(inserts, options)
end

#insert_one(document, opts = {}) ⇒ Result

Insert a single document into the collection.

Examples:

Insert a document into the collection.

collection.insert_one({ name: 'test' })

Parameters:

  • document (Hash)

    The document to insert.

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

    The insert options.

  • options (Hash)

    a customizable set of options

Options Hash (opts):

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :session (Session)

    The session to use for the operation.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer, :fsync => Boolean, :j => Boolean.

Returns:

  • (Result)

    The database response wrapper.

Since:

  • 2.0.0



849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
# File 'lib/mongo/collection.rb', line 849

def insert_one(document, opts = {})
  QueryCache.clear_namespace(namespace)

  client.with_session(opts) do |session|
    write_concern = if opts[:write_concern]
      WriteConcern.get(opts[:write_concern])
    else
      write_concern_with_session(session)
    end

    if document.nil?
      raise ArgumentError, "Document to be inserted cannot be nil"
    end

    context = Operation::Context.new(
      client: client,
      session: session,
      operation_timeouts: operation_timeouts(opts)
      )
    write_with_retry(write_concern, context: context) do |connection, txn_num, context|
      Operation::Insert.new(
        :documents => [ document ],
        :db_name => database.name,
        :coll_name => name,
        :write_concern => write_concern,
        :bypass_document_validation => !!opts[:bypass_document_validation],
        :options => opts,
        :id_generator => client.options[:id_generator],
        :session => session,
        :txn_num => txn_num,
        :comment => opts[:comment]
      ).execute_with_connection(connection, context: context)
    end
  end
end

#inspectString

Get a pretty printed string inspection for the collection.

Examples:

Inspect the collection.

collection.inspect

Returns:

  • (String)

    The collection inspection.

Since:

  • 2.0.0



822
823
824
# File 'lib/mongo/collection.rb', line 822

def inspect
  "#<Mongo::Collection:0x#{object_id} namespace=#{namespace}>"
end

#namespaceString

Get the fully qualified namespace of the collection.

Examples:

Get the fully qualified namespace.

collection.namespace

Returns:

  • (String)

    The collection namespace.

Since:

  • 2.0.0



1255
1256
1257
# File 'lib/mongo/collection.rb', line 1255

def namespace
  "#{database.name}.#{name}"
end

#operation_timeouts(opts = {}) ⇒ Hash

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.

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

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



1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
# File 'lib/mongo/collection.rb', line 1280

def operation_timeouts(opts = {})
  # TODO: We should re-evaluate if we need two timeouts separately.
  {}.tap do |result|
    if opts[:timeout_ms].nil?
      result[:inherited_timeout_ms] = timeout_ms
    else
      result[:operation_timeout_ms] = opts.delete(:timeout_ms)
    end
  end
end

#parallel_scan(cursor_count, options = {}) ⇒ Array<Cursor>

Execute a parallel scan on the collection view.

Returns a list of up to cursor_count cursors that can be iterated concurrently. As long as the collection is not modified during scanning, each document appears once in one of the cursors’ result sets.

Examples:

Execute a parallel collection scan.

collection.parallel_scan(2)

Parameters:

  • cursor_count (Integer)

    The max number of cursors to return.

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

    The parallel scan command options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the query to run, in milliseconds. This option is deprecated, use :timeout_ms instead.

  • :session (Session)

    The session to use.

  • :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.

Returns:

  • (Array<Cursor>)

    An array of cursors.

Since:

  • 2.1



1025
1026
1027
# File 'lib/mongo/collection.rb', line 1025

def parallel_scan(cursor_count, options = {})
  find({}, options).parallel_scan(cursor_count, options)
end

#read_concernHash

Get the effective read concern for this collection instance.

If a read concern was provided in collection options, that read concern will be returned, otherwise the database’s effective read concern will be returned.

Examples:

Get the read concern.

collection.read_concern

Returns:

  • (Hash)

    The read concern.

Since:

  • 2.2.0



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

def read_concern
  options[:read_concern] || database.read_concern
end

#read_preferenceHash

Get the effective read preference for this collection.

If a read preference was provided in collection options, that read preference will be returned, otherwise the database’s effective read preference will be returned.

Examples:

Get the read preference.

collection.read_preference

Returns:

  • (Hash)

    The read preference.

Since:

  • 2.0.0



221
222
223
# File 'lib/mongo/collection.rb', line 221

def read_preference
  @read_preference ||= options[:read] || database.read_preference
end

#replace_one(filter, replacement, options = {}) ⇒ Result

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

Examples:

Replace a single document.

collection.replace_one({ name: 'test' }, { name: 'test1' })

Parameters:

  • filter (Hash)

    The filter to use.

  • replacement (Hash)

    The replacement document..

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

    The options.

Options Hash (options):

  • :upsert (true | false)

    Whether to upsert if the document doesn’t exist.

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

  • :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.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



1056
1057
1058
# File 'lib/mongo/collection.rb', line 1056

def replace_one(filter, replacement, options = {})
  find(filter, options).replace_one(replacement, options)
end

#search_indexes(options = {}) ⇒ SearchIndex::View

Note:

Only one of id or name may be given; it is an error to specify both, although both may be omitted safely.

Get a view of all search indexes for this collection. Can be iterated or operated on directly. If id or name are given, the iterator will return only the indicated index. For all other operations, id and name are ignored.

Parameters:

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

    The options to use to configure the view.

Options Hash (options):

  • :id (String)

    The id of the specific index to query (optional)

  • :name (String)

    The name of the specific index to query (optional)

  • :aggregate (Hash)

    The options hash to pass to the aggregate command (optional)

Returns:

Since:

  • 2.0.0



810
811
812
# File 'lib/mongo/collection.rb', line 810

def search_indexes(options = {})
  SearchIndex::View.new(self, options)
end

#server_selectorMongo::ServerSelector

Get the server selector for this collection.

Examples:

Get the server selector.

collection.server_selector

Returns:

Since:

  • 2.0.0



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

def server_selector
  @server_selector ||= ServerSelector.get(read_preference || database.server_selector)
end

#system_collection?Boolean

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.

Whether the collection is a system collection.

Returns:

  • (Boolean)

    Whether the system is a system collection.

Since:

  • 2.0.0



1264
1265
1266
# File 'lib/mongo/collection.rb', line 1264

def system_collection?
  name.start_with?('system.')
end

#timeout_msInteger | nil

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.

Returns Operation timeout that is for this database or for the corresponding client.

Returns:

  • (Integer | nil)

    Operation timeout that is for this database or for the corresponding client.

Since:

  • 2.0.0



1272
1273
1274
# File 'lib/mongo/collection.rb', line 1272

def timeout_ms
  @timeout_ms || database.timeout_ms
end

#update_many(filter, update, options = {}) ⇒ Result

Update documents in the collection.

Examples:

Update multiple documents in the collection.

collection.update_many({ name: 'test'}, '$set' => { name: 'test1' })

Parameters:

  • filter (Hash)

    The filter to use.

  • update (Hash | Array<Hash>)

    The update document or pipeline.

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

    The options.

Options Hash (options):

  • :upsert (true | false)

    Whether to upsert if the document doesn’t exist.

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

  • :array_filters (Array)

    A set of filters specifying to which array elements an update should apply.

  • :session (Session)

    The session to use.

  • :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.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



1089
1090
1091
# File 'lib/mongo/collection.rb', line 1089

def update_many(filter, update, options = {})
  find(filter, options).update_many(update, options)
end

#update_one(filter, update, options = {}) ⇒ Result

Update a single document in the collection.

Examples:

Update a single document in the collection.

collection.update_one({ name: 'test'}, '$set' => { name: 'test1'})

Parameters:

  • filter (Hash)

    The filter to use.

  • update (Hash | Array<Hash>)

    The update document or pipeline.

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

    The options.

Options Hash (options):

  • :upsert (true | false)

    Whether to upsert if the document doesn’t exist.

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

  • :array_filters (Array)

    A set of filters specifying to which array elements an update should apply.

  • :session (Session)

    The session to use.

  • :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.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



1122
1123
1124
# File 'lib/mongo/collection.rb', line 1122

def update_one(filter, update, options = {})
  find(filter, options).update_one(update, options)
end

#watch(pipeline = [], options = {}) ⇒ ChangeStream

Note:

A change stream only allows ‘majority’ read concern.

Note:

This helper method is preferable to running a raw aggregation with a $changeStream stage, for the purpose of supporting resumability.

As of version 3.6 of the MongoDB server, a “$changeStream“ pipeline stage is supported in the aggregation framework. This stage allows users to request that notifications are sent for all changes to a particular collection.

Examples:

Get change notifications for a given collection.

collection.watch([{ '$match' => { operationType: { '$in' => ['insert', 'replace'] } } }])

Parameters:

  • pipeline (Array<Hash>) (defaults to: [])

    Optional additional filter operators.

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

    The change stream options.

Options Hash (options):

  • :full_document (String)

    Allowed values: nil, ‘default’, ‘updateLookup’, ‘whenAvailable’, ‘required’.

    The default is to not send a value (i.e. nil), which is equivalent to ‘default’. By default, the change notification for partial updates will include a delta describing the changes to the document.

    When set to ‘updateLookup’, the change notification for partial updates will include both a delta describing the changes to the document as well as a copy of the entire document that was changed from some time after the change occurred.

    When set to ‘whenAvailable’, configures the change stream to return the post-image of the modified document for replace and update change events if the post-image for this event is available.

    When set to ‘required’, the same behavior as ‘whenAvailable’ except that an error is raised if the post-image is not available.

  • :full_document_before_change (String)

    Allowed values: nil, ‘whenAvailable’, ‘required’, ‘off’.

    The default is to not send a value (i.e. nil), which is equivalent to ‘off’.

    When set to ‘whenAvailable’, configures the change stream to return the pre-image of the modified document for replace, update, and delete change events if it is available.

    When set to ‘required’, the same behavior as ‘whenAvailable’ except that an error is raised if the pre-image is not available.

  • :resume_after (BSON::Document, Hash)

    Specifies the logical starting point for the new change stream.

  • :max_await_time_ms (Integer)

    The maximum amount of time for the server to wait on new documents to satisfy a change stream query.

  • :batch_size (Integer)

    The number of documents to return per batch.

  • :collation (BSON::Document, Hash)

    The collation to use.

  • :session (Session)

    The session to use.

  • :start_at_operation_time (BSON::Timestamp)

    Only return changes that occurred at or after the specified timestamp. Any command run against the server will return a cluster time that can be used here. Only recognized by server versions 4.0+.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :show_expanded_events (Boolean)

    Enables the server to send the ‘expanded’ list of change stream events. The list of additional events included with this flag set are: createIndexes, dropIndexes, modify, create, shardCollection, reshardCollection, refineCollectionShardKey.

  • :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.

Returns:

  • (ChangeStream)

    The change stream object.

Since:

  • 2.5.0



646
647
648
649
650
# File 'lib/mongo/collection.rb', line 646

def watch(pipeline = [], options = {})
  view_options = options.dup
  view_options[:cursor_type] = :tailable_await if options[:max_await_time_ms]
  View::ChangeStream.new(View.new(self, {}, view_options), pipeline, nil, options)
end

#with(new_options) ⇒ Mongo::Collection

Returns A new collection instance.

Examples:

Get a collection with a changed read concern.

collection.with(read_concern: { level: :majority })

Get a collection with a changed write concern.

collection.with(write_concern: { w:  3 })

Parameters:

  • new_options (Hash)

    The new options to use.

Options Hash (new_options):

  • :read (Hash)

    The read preference options. The hash may have the following items:

    • :mode – read preference specified as a symbol; valid values are :primary, :primary_preferred, :secondary, :secondary_preferred and :nearest.

    • :tag_sets – an array of hashes.

    • :local_threshold.

  • :read_concern (Hash)

    The read concern options hash, with the following optional keys:

    • :level – the read preference level as a symbol; valid values

      are *:local*, *:majority*, and *:snapshot*
      
  • :write (Hash)

    Deprecated. Equivalent to :write_concern option.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer|String, :fsync => Boolean, :j => Boolean.

Returns:

Since:

  • 2.1.0



299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/mongo/collection.rb', line 299

def with(new_options)
  new_options.keys.each do |k|
    raise Error::UnchangeableCollectionOption.new(k) unless CHANGEABLE_OPTIONS.include?(k)
  end
  options = @options.dup
  if options[:write] && new_options[:write_concern]
    options.delete(:write)
  end
  if options[:write_concern] && new_options[:write]
    options.delete(:write_concern)
  end
  Collection.new(database, name, options.update(new_options))
end

#write_concernMongo::WriteConcern

Get the effective write concern on this collection.

If a write concern was provided in collection options, that write concern will be returned, otherwise the database’s effective write concern will be returned.

Examples:

Get the write concern.

collection.write_concern

Returns:

Since:

  • 2.0.0



237
238
239
240
# File 'lib/mongo/collection.rb', line 237

def write_concern
  @write_concern ||= WriteConcern.get(
    options[:write_concern] || options[:write] || database.write_concern)
end

#write_concern_with_session(session) ⇒ Mongo::WriteConcern

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.

Get the write concern to use for an operation on this collection, given a session.

If the session is in a transaction and the collection has an unacknowledged write concern, remove the write concern’s :w option. Otherwise, return the unmodified write concern.

Returns:

Since:

  • 2.0.0



253
254
255
256
257
258
259
260
261
262
263
# File 'lib/mongo/collection.rb', line 253

def write_concern_with_session(session)
  wc = write_concern
  if session && session.in_transaction?
    if wc && !wc.acknowledged?
      opts = wc.options.dup
      opts.delete(:w)
      return WriteConcern.get(opts)
    end
  end
  wc
end