Class: Mongo::Collection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Retryable
Defined in:
lib/mongo/collection.rb,
lib/mongo/collection/view.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/builder/flags.rb,
lib/mongo/collection/view/change_stream.rb,
lib/mongo/collection/view/builder/op_query.rb,
lib/mongo/collection/view/builder/modifiers.rb,
lib/mongo/collection/view/builder/map_reduce.rb,
lib/mongo/collection/view/builder/aggregation.rb,
lib/mongo/collection/view/builder/find_command.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

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Retryable

#legacy_write_with_retry, #nro_write_with_retry, #read_with_one_retry, #read_with_retry, #read_with_retry_cursor, #write_with_retry

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.

Options Hash (options):

  • :write (Hash)

    Deprecated. Equivalent to :write_concern option.

  • :write_concern (Hash)

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

Raises:

Since:

  • 2.0.0



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/mongo/collection.rb', line 89

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
=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



39
40
41
# File 'lib/mongo/collection.rb', line 39

def database
  @database
end

#nameString (readonly)

Returns The name of the collection.

Returns:

  • (String)

    The name of the collection.

Since:

  • 2.0.0



42
43
44
# File 'lib/mongo/collection.rb', line 42

def name
  @name
end

#optionsHash (readonly)

Returns The collection options.

Returns:

  • (Hash)

    The collection options.

Since:

  • 2.0.0



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

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



69
70
71
72
# File 'lib/mongo/collection.rb', line 69

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

#aggregate(pipeline, options = {}) ⇒ 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 (String)

    Associate a comment with the aggregation.

  • :hint (String)

    The index to use for the aggregation.

  • :max_time_ms (Integer)

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

  • :use_cursor (true, false)

    Indicates whether the command will request that the server provide results using a cursor. Note that as of server version 3.6, aggregations always provide results using a cursor and this option is therefore not valid.

  • :session (Session)

    The session to use.

Returns:

  • (Aggregation)

    The aggregation object.

Since:

  • 2.1.0



355
356
357
# File 'lib/mongo/collection.rb', line 355

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 (Array<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.

Returns:

Since:

  • 2.0.0



590
591
592
# File 'lib/mongo/collection.rb', line 590

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



214
215
216
# File 'lib/mongo/collection.rb', line 214

def capped?
  database.read_command(:collstats => name).documents[0][CAPPED]
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 the 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 command to run.

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

Returns:

  • (Integer)

    The document count.

Since:

  • 2.1.0



424
425
426
# File 'lib/mongo/collection.rb', line 424

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

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

Gets the number of of matching documents in the collection. Unlike the deprecated #count method, this will return the exact number of documents matching the filter rather than the estimate.

Examples:

Get the number of documents in the collection.

collection_view.count_documents

Parameters:

  • filter (Hash)

    A filter for matching documents.

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

    Options for the operation.

  • opts (Hash)

    a customizable set of options

Returns:

  • (Integer)

    The document count.

Since:

  • 2.6.0



449
450
451
# File 'lib/mongo/collection.rb', line 449

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)

    a customizable set of options

Returns:

  • (Result)

    The result of the command.

Since:

  • 2.0.0



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/mongo/collection.rb', line 230

def create(opts = {})
  # Passing read options to create command causes it to break.
  # Filter the read options out.
  # 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.reject do |key, value|
    %w(read read_preference).include?(key.to_s)
  end]
  operation = { :create => name }.merge(options)
  operation.delete(:write)
  operation.delete(:write_concern)
  client.send(:with_session, opts) do |session|
    server = next_primary(nil, session)
    if (options[:collation] || options[Operation::COLLATION]) && !server.features.collation_enabled?
      raise Error::UnsupportedCollation
    end

    Operation::Create.new({
                            selector: operation,
                            db_name: database.name,
                            write_concern: write_concern,
                            session: session
                            }).execute(server, client: client)
  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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



626
627
628
# File 'lib/mongo/collection.rb', line 626

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



608
609
610
# File 'lib/mongo/collection.rb', line 608

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 command to run.

  • :read (Hash)

    The read preference options.

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

Returns:

  • (Array<Object>)

    The list of distinct values.

Since:

  • 2.1.0



488
489
490
# File 'lib/mongo/collection.rb', line 488

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.

Examples:

Drop the collection.

collection.drop

Parameters:

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

    The options for the drop operation.

  • options (Hash)

    a customizable set of options

Returns:

  • (Result)

    The result of the command.

Since:

  • 2.0.0



271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/mongo/collection.rb', line 271

def drop(opts = {})
  client.send(:with_session, opts) do |session|
    Operation::Drop.new({
                          selector: { :drop => name },
                          db_name: database.name,
                          write_concern: write_concern,
                          session: session
                          }).execute(next_primary(nil, session), client: client)
  end
rescue Error::OperationFailure => ex
  raise ex unless ex.message =~ /ns not found/
  false
end

#estimated_document_count(options = {}) ⇒ Integer

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

Examples:

Get the number of documents in the collection.

collection_view.estimated_document_count

Parameters:

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

    Options for the operation.

  • opts (Hash)

    a customizable set of options

Returns:

  • (Integer)

    The document count.

Since:

  • 2.6.0



467
468
469
# File 'lib/mongo/collection.rb', line 467

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_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.

  • :comment (String)

    Associate a comment with the query.

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

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

    Internal replication use only - driver should not set.

  • :projection (Hash)

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

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

  • :collation (Hash)

    The collation to use.

  • :session (Session)

    The session to use.

Returns:

  • (CollectionView)

    The collection view.

Since:

  • 2.0.0



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

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

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

Returns:

  • (BSON::Document, nil)

    The document, if found.

Since:

  • 2.1.0



748
749
750
# File 'lib/mongo/collection.rb', line 748

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.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



818
819
820
# File 'lib/mongo/collection.rb', line 818

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.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



784
785
786
# File 'lib/mongo/collection.rb', line 784

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

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

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:

  • (View::Index)

    The index view.

Since:

  • 2.0.0



505
506
507
# File 'lib/mongo/collection.rb', line 505

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 (Array<Hash>)

    The documents to insert.

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

    The insert options.

Options Hash (options):

  • :session (Session)

    The session to use for the operation.

Returns:

  • (Result)

    The database response wrapper.

Since:

  • 2.0.0



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

def insert_many(documents, options = {})
  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 (opts):

  • :session (Session)

    The session to use for the operation.

Returns:

  • (Result)

    The database response wrapper.

Since:

  • 2.0.0



534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'lib/mongo/collection.rb', line 534

def insert_one(document, opts = {})
  client.send(:with_session, opts) do |session|
    write_concern = write_concern_with_session(session)
    write_with_retry(session, write_concern) do |server, txn_num|
      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
       ).execute(server, client: client)
    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



517
518
519
# File 'lib/mongo/collection.rb', line 517

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



830
831
832
# File 'lib/mongo/collection.rb', line 830

def namespace
  "#{database.name}.#{name}"
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 command to run in milliseconds.

  • :session (Session)

    The session to use.

Returns:

  • (Array<Cursor>)

    An array of cursors.

Since:

  • 2.1



649
650
651
# File 'lib/mongo/collection.rb', line 649

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

#read_concernHash

Get the read concern for this collection instance.

Examples:

Get the read concern.

collection.read_concern

Returns:

  • (Hash)

    The read concern.

Since:

  • 2.2.0



115
116
117
# File 'lib/mongo/collection.rb', line 115

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

#read_preferenceHash

Get the read preference on this collection.

Examples:

Get the read preference.

collection.read_preference

Returns:

  • (Hash)

    The read preference.

Since:

  • 2.0.0



139
140
141
# File 'lib/mongo/collection.rb', line 139

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



672
673
674
# File 'lib/mongo/collection.rb', line 672

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

#server_selectorMongo::ServerSelector

Get the server selector on this collection.

Examples:

Get the server selector.

collection.server_selector

Returns:

Since:

  • 2.0.0



127
128
129
# File 'lib/mongo/collection.rb', line 127

def server_selector
  @server_selector ||= ServerSelector.get(read_preference || database.server_selector)
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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



697
698
699
# File 'lib/mongo/collection.rb', line 697

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



722
723
724
# File 'lib/mongo/collection.rb', line 722

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: ‘default’, ‘updateLookup’. Defaults to ‘default’. 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.

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

Returns:

  • (ChangeStream)

    The change stream object.

Since:

  • 2.5.0



395
396
397
# File 'lib/mongo/collection.rb', line 395

def watch(pipeline = [], options = {})
  View::ChangeStream.new(View.new(self, {}, options), pipeline, nil, options)
end

#with(new_options) ⇒ Mongo::Collection

Returns A new collection instance.

Parameters:

  • new_options (Hash)

    The new options to use.

Returns:

Since:

  • 2.1.0



192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/mongo/collection.rb', line 192

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 write concern on this collection.

Examples:

Get the write concern.

collection.write_concern

Returns:

Since:

  • 2.0.0



151
152
153
154
# File 'lib/mongo/collection.rb', line 151

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 for the collection, given the 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



166
167
168
169
170
171
172
173
174
175
176
# File 'lib/mongo/collection.rb', line 166

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