Class: Mongo::Collection
| Relationships & Source Files | |
| Namespace Children | |
|
Modules:
| |
|
Classes:
| |
| Super Chains via Extension / Inclusion / Inheritance | |
|
Class Chain:
self,
Forwardable
|
|
|
Instance Chain:
|
|
| Inherits: | Object |
| Defined in: | lib/mongo/collection.rb, lib/mongo/collection/helpers.rb, lib/mongo/collection/queryable_encryption.rb, lib/mongo/collection/view.rb, lib/mongo/collection/view/aggregation.rb, lib/mongo/collection/view/change_stream.rb, lib/mongo/collection/view/explainable.rb, lib/mongo/collection/view/immutable.rb, lib/mongo/collection/view/iterable.rb, lib/mongo/collection/view/map_reduce.rb, lib/mongo/collection/view/readable.rb, lib/mongo/collection/view/writable.rb, lib/mongo/collection/view/aggregation/behavior.rb, lib/mongo/collection/view/builder/aggregation.rb, lib/mongo/collection/view/builder/map_reduce.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.
Constant Summary
-
CAPPED =
# File 'lib/mongo/collection.rb', line 36
The capped option.
'capped' -
CHANGEABLE_OPTIONS =
# File 'lib/mongo/collection.rb', line 63
Optionsthat can be updated on a newCollectioninstance via the #with method.%i[read read_concern write write_concern].freeze
-
CREATE_COLLECTION_OPTIONS =
Internal use only
# File 'lib/mongo/collection.rb', line 68
Optionsmap to transform create collection options.{ time_series: :timeseries, expire_after: :expireAfterSeconds, clustered_index: :clusteredIndex, change_stream_pre_and_post_images: :changeStreamPreAndPostImages, encrypted_fields: :encryptedFields, validator: :validator, view_on: :viewOn } -
NS =
# File 'lib/mongo/collection.rb', line 41
The ns field constant.
'ns'
QueryableEncryption - Included
Class Method Summary
-
.new(database, name, options = {}) ⇒ Collection
constructor
Instantiate a new collection.
Instance Attribute Summary
-
#capped? ⇒ true | false
readonly
Is the collection capped?
- #database ⇒ Mongo::Database readonly
- #name ⇒ String readonly
- #options ⇒ Hash readonly
-
#system_collection? ⇒ Boolean
readonly
Internal use only
Internal use only
Whether the collection is a system collection.
Instance Method Summary
-
#==(other) ⇒ true | false
Check if a collection is equal to another object.
-
#aggregate(pipeline, options = {}) ⇒ View::Aggregation
Perform an aggregation on the collection.
-
#bulk_write(requests, options = {}) ⇒ BulkWrite::Result
Execute a batch of bulk write operations.
-
#count(filter = nil, options = {}) ⇒ Integer
deprecated
Deprecated.
Use #count_documents or estimated_document_count instead. However, note that the following operators will need to be substituted when switching to #count_documents:
* $where should be replaced with $expr * $near should be replaced with $geoWithin with $center * $nearSphere should be replaced with $geoWithin with $centerSphere -
#count_documents(filter = {}, options = {}) ⇒ Integer
Gets the number of documents matching the query.
-
#create(opts = {}) ⇒ Result
Force the collection to be created in the database.
-
#delete_many(filter = nil, options = {}) ⇒ Result
Remove documents from the collection.
-
#delete_one(filter = nil, options = {}) ⇒ Result
Remove a document from the collection.
-
#distinct(field_name, filter = nil, options = {}) ⇒ Array<Object>
Get a list of distinct values for a specific field.
-
#drop(opts = {}) ⇒ Result
Drop the collection.
-
#estimated_document_count(options = {}) ⇒ Integer
Gets an estimate of the number of documents in the collection using the collection metadata.
-
#find(filter = nil, options = {}) ⇒ CollectionView
Find documents in the collection.
-
#find_one_and_delete(filter, options = {}) ⇒ BSON::Document?
Finds a single document in the database via findAndModify and deletes it, returning the original document.
-
#find_one_and_replace(filter, replacement, options = {}) ⇒ BSON::Document
Finds a single document and replaces it, returning the original doc unless otherwise specified.
-
#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.
-
#indexes(options = {}) ⇒ Index::View
Get a view of all indexes for this collection.
-
#insert_many(documents, options = {}) ⇒ Result
Insert the provided documents into the collection.
-
#insert_one(document, opts = {}) ⇒ Result
Insert a single document into the collection.
-
#inspect ⇒ String
Get a pretty printed string inspection for the collection.
-
#namespace ⇒ String
Get the fully qualified namespace of the collection.
- #operation_timeouts(opts = {}) ⇒ Hash Internal use only Internal use only
-
#parallel_scan(cursor_count, options = {}) ⇒ Array<Cursor>
Execute a parallel scan on the collection view.
-
#read_concern ⇒ Hash
Get the effective read concern for this collection instance.
-
#read_preference ⇒ Hash
Get the effective read preference for this collection.
-
#replace_one(filter, replacement, options = {}) ⇒ Result
Replaces a single document in the collection with the new document.
-
#search_indexes(options = {}) ⇒ SearchIndex::View
Get a view of all search indexes for this collection.
-
#server_selector ⇒ Mongo::ServerSelector
Get the server selector for this collection.
- #timeout_ms ⇒ Integer | nil Internal use only Internal use only
-
#update_many(filter, update, options = {}) ⇒ Result
Update documents in the collection.
-
#update_one(filter, update, options = {}) ⇒ Result
Update a single document in the collection.
-
#watch(pipeline = [], options = {}) ⇒ ChangeStream
Allows users to request that notifications are sent for all changes to a particular collection.
- #with(new_options) ⇒ Mongo::Collection
-
#write_concern ⇒ Mongo::WriteConcern
Get the effective write concern on this collection.
-
#write_concern_with_session(session) ⇒ Mongo::WriteConcern
Internal use only
Internal use only
Get the write concern to use for an operation on this collection, given a session.
Helpers - Included
| #do_drop | Executes drop operation and and ignores NamespaceNotFound error. |
QueryableEncryption - Included
| #maybe_create_qe_collections | Creates auxiliary collections and indices for queryable encryption if necessary. |
| #maybe_drop_emm_collections | Drops auxiliary collections and indices for queryable encryption if necessary. |
| #check_wire_version! | Creating encrypted collections is only supported on 7.0.0 and later (wire version 21+). |
| #create_operation_for | Returns a new create operation for the given collection. |
| #emm_collections | Checks if names for auxiliary collections are set and returns them, otherwise returns default names. |
| #encrypted_fields_for_drop_from_map | Tries to return the encrypted fields from the |
| #encrypted_fields_from | Tries to return the encrypted fields from the argument. |
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. |
| #with_overload_retry | Wraps an operation with overload retry logic. |
| #write_worker | Returns the write worker for handling retryable writes. |
| #deprioritize_server? | Whether the failed server should be deprioritized during server selection for a retry attempt. |
Constructor Details
.new(database, name, options = {}) ⇒ Collection
Instantiate a new collection.
# File 'lib/mongo/collection.rb', line 163
def initialize(database, name, = {}) raise Error::InvalidCollectionName.new unless name if [:write] && [:write_concern] && [:write] != [:write_concern] raise ArgumentError, "If :write and :write_concern are both given, they must be identical: #{.inspect}" end @database = database @name = name.to_s.freeze @options = .dup @timeout_ms = .delete(:timeout_ms) # 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 @options.freeze end
Instance Attribute Details
#capped? ⇒ true | false (readonly)
Is the collection capped?
#database ⇒ Mongo::Database (readonly)
# File 'lib/mongo/collection.rb', line 44
attr_reader :database
#name ⇒ String (readonly)
# File 'lib/mongo/collection.rb', line 47
attr_reader :name
#options ⇒ Hash (readonly)
# File 'lib/mongo/collection.rb', line 50
attr_reader :
#system_collection? ⇒ Boolean (readonly)
Whether the collection is a system collection.
# File 'lib/mongo/collection.rb', line 1271
def system_collection? name.start_with?('system.') 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.
#aggregate(pipeline, options = {}) ⇒ View::Aggregation
Perform an aggregation on the collection.
#bulk_write(requests, options = {}) ⇒ BulkWrite::Result
Execute a batch of bulk write operations.
#count(filter = nil, options = {}) ⇒ Integer
Use #count_documents or estimated_document_count instead. However, note that the following operators will need to be substituted when switching to #count_documents:
* $where should be replaced with $expr
* $near should be replaced with $geoWithin with $center
* $nearSphere should be replaced with $geoWithin with $centerSphere
Gets an estimated number of matching documents in the collection.
#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.
# File 'lib/mongo/collection.rb', line 715
def count_documents(filter = {}, = {}) View.new(self, filter, ).count_documents() end
#create(opts = {}) ⇒ Result
Force the collection to be created in the database.
# File 'lib/mongo/collection.rb', line 378
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. = Hash[self..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| [server_key] = .delete(ruby_key) if .key?(ruby_key) end operation = { create: name }.merge() 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 ) operation = 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: [:collation] || ['collation'], validator: [:validator] ) tracer.trace_operation(operation, context, op_name: 'createCollection') do maybe_create_qe_collections(opts[:encrypted_fields], client, session) do |encrypted_fields| operation.encrypted_fields = encrypted_fields operation.execute( next_primary(nil, session), context: context ) end end end end
#delete_many(filter = nil, options = {}) ⇒ Result
Remove documents from the collection.
# File 'lib/mongo/collection.rb', line 991
def delete_many(filter = nil, = {}) find(filter, ).delete_many() end
#delete_one(filter = nil, options = {}) ⇒ Result
Remove a document from the collection.
# File 'lib/mongo/collection.rb', line 965
def delete_one(filter = nil, = {}) find(filter, ).delete_one() end
#distinct(field_name, filter = nil, options = {}) ⇒ Array<Object>
Get a list of distinct values for a specific field.
#drop(opts = {}) ⇒ Result
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.
# File 'lib/mongo/collection.rb', line 451
def drop(opts = {}) client.with_session(opts) do |session| context = Operation::Context.new( client: client, session: session, operation_timeouts: operation_timeouts(opts) ) temp_write_concern = write_concern write_concern = if opts[:write_concern] WriteConcern.get(opts[:write_concern]) else temp_write_concern end operation = Operation::Drop.new({ selector: { drop: name }, db_name: database.name, write_concern: write_concern, session: session, }) tracer.trace_operation(operation, context, op_name: 'dropCollection') do maybe_drop_emm_collections(opts[:encrypted_fields], client, session) do do_drop(operation, session, context) end 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.
# File 'lib/mongo/collection.rb', line 740
def estimated_document_count( = {}) View.new(self, {}, ).estimated_document_count() end
#find(filter = nil, options = {}) ⇒ CollectionView
Find documents in the collection.
#find_one_and_delete(filter, options = {}) ⇒ BSON::Document?
Finds a single document in the database via findAndModify and deletes it, returning the original document.
# File 'lib/mongo/collection.rb', line 1164
def find_one_and_delete(filter, = {}) find(filter, ).find_one_and_delete() end
#find_one_and_replace(filter, replacement, options = {}) ⇒ BSON::Document
Finds a single document and replaces it, returning the original doc unless otherwise specified.
# File 'lib/mongo/collection.rb', line 1250
def find_one_and_replace(filter, replacement, = {}) find(filter, ).find_one_and_update(replacement, ) 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.
# File 'lib/mongo/collection.rb', line 1208
def find_one_and_update(filter, update, = {}) find(filter, ).find_one_and_update(update, ) end
#indexes(options = {}) ⇒ Index::View
Get a view of all indexes for this collection. Can be iterated or has more operations.
#insert_many(documents, options = {}) ⇒ Result
Insert the provided documents into the collection.
# File 'lib/mongo/collection.rb', line 907
def insert_many(documents, = {}) QueryCache.clear_namespace(namespace) inserts = documents.map { |doc| { insert_one: doc } } bulk_write(inserts, ) end
#insert_one(document, opts = {}) ⇒ Result
Insert a single document into the collection.
# File 'lib/mongo/collection.rb', line 845
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 raise ArgumentError, 'Document to be inserted cannot be nil' if document.nil? context = Operation::Context.new( client: client, session: session, operation_timeouts: operation_timeouts(opts) ) operation = 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.[:id_generator], session: session, comment: opts[:comment] ) tracer.trace_operation(operation, context) do write_with_retry(write_concern, context: context) do |connection, txn_num, context| operation.txn_num = txn_num operation.execute_with_connection(connection, context: context) end end end end
#inspect ⇒ String
Get a pretty printed string inspection for the collection.
# File 'lib/mongo/collection.rb', line 818
def inspect "#<Mongo::Collection:0x#{object_id} namespace=#{namespace}>" end
#namespace ⇒ String
Get the fully qualified namespace of the collection.
#operation_timeouts(opts = {}) ⇒ Hash
# File 'lib/mongo/collection.rb', line 1287
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.
# File 'lib/mongo/collection.rb', line 1022
def parallel_scan(cursor_count, = {}) find({}, ).parallel_scan(cursor_count, ) end
#read_concern ⇒ Hash
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.
# File 'lib/mongo/collection.rb', line 194
def read_concern [:read_concern] || database.read_concern end
#read_preference ⇒ Hash
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.
# File 'lib/mongo/collection.rb', line 222
def read_preference @read_preference ||= [:read] || database.read_preference end
#replace_one(filter, replacement, options = {}) ⇒ Result
Replaces a single document in the collection with the new document.
# File 'lib/mongo/collection.rb', line 1058
def replace_one(filter, replacement, = {}) find(filter, ).replace_one(replacement, ) end
#search_indexes(options = {}) ⇒ SearchIndex::View
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.
# File 'lib/mongo/collection.rb', line 806
def search_indexes( = {}) SearchIndex::View.new(self, ) end
#server_selector ⇒ Mongo::ServerSelector
Get the server selector for this collection.
# File 'lib/mongo/collection.rb', line 206
def server_selector @server_selector ||= ServerSelector.get(read_preference || database.server_selector) end
#timeout_ms ⇒ Integer | nil
# File 'lib/mongo/collection.rb', line 1279
def timeout_ms @timeout_ms || database.timeout_ms end
#update_many(filter, update, options = {}) ⇒ Result
Update documents in the collection.
# File 'lib/mongo/collection.rb', line 1091
def update_many(filter, update, = {}) find(filter, ).update_many(update, ) end
#update_one(filter, update, options = {}) ⇒ Result
Update a single document in the collection.
# File 'lib/mongo/collection.rb', line 1129
def update_one(filter, update, = {}) find(filter, ).update_one(update, ) end
#watch(pipeline = [], options = {}) ⇒ ChangeStream
A change stream only allows ‘majority’ read concern.
This helper method is preferable to running a raw aggregation with a $changeStream stage, for the purpose of supporting resumability.
Allows users to request that notifications are sent for all changes to a particular collection.
# File 'lib/mongo/collection.rb', line 642
def watch(pipeline = [], = {}) = .dup [:cursor_type] = :tailable_await if [:max_await_time_ms] View::ChangeStream.new(View.new(self, {}, ), pipeline, nil, ) end
#with(new_options) ⇒ Collection
# File 'lib/mongo/collection.rb', line 299
def with() .keys.each do |k| raise Error::UnchangeableCollectionOption.new(k) unless CHANGEABLE_OPTIONS.include?(k) end = @options.dup .delete(:write) if [:write] && [:write_concern] .delete(:write_concern) if [:write_concern] && [:write] Collection.new(database, name, .update()) end
#write_concern ⇒ Mongo::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.
# File 'lib/mongo/collection.rb', line 238
def write_concern @write_concern ||= WriteConcern.get( [:write_concern] || [:write] || database.write_concern ) end
#write_concern_with_session(session) ⇒ Mongo::WriteConcern
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.
# File 'lib/mongo/collection.rb', line 255
def write_concern_with_session(session) wc = write_concern if session && session.in_transaction? && wc && !wc.acknowledged? opts = wc..dup opts.delete(:w) return WriteConcern.get(opts) end wc end