Class: Mongo::Collection
- Inherits:
-
Object
- Object
- Mongo::Collection
- 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.
Defined Under Namespace
Modules: Helpers, QueryableEncryption Classes: View
Constant Summary collapse
- CAPPED =
The capped option.
'capped'.freeze
- NS =
The ns field constant.
'ns'.freeze
- CHANGEABLE_OPTIONS =
Options that can be updated on a new Collection instance via the #with method.
[ :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.
{ :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
-
#database ⇒ Mongo::Database
readonly
The database the collection resides in.
-
#name ⇒ String
readonly
The name of the collection.
-
#options ⇒ Hash
readonly
The collection options.
Instance Method Summary collapse
-
#==(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.
-
#capped? ⇒ true | false
Is the collection capped?.
-
#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 (only works on 3.6+) * $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.
-
#initialize(database, name, options = {}) ⇒ Collection
constructor
Instantiate a new 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
private
Timeout_ms value set on the operation level (if any), and/or timeout_ms that is set on collection/database/client level (if any).
-
#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.
-
#system_collection? ⇒ Boolean
private
Whether the collection is a system collection.
-
#timeout_ms ⇒ Integer | nil
private
Operation timeout that is for this database or for the corresponding client.
-
#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
As of version 3.6 of the MongoDB server, a “$changeStream“ pipeline stage is supported in the aggregation framework.
-
#with(new_options) ⇒ Mongo::Collection
A new collection instance.
-
#write_concern ⇒ Mongo::WriteConcern
Get the effective write concern on this collection.
-
#write_concern_with_session(session) ⇒ Mongo::WriteConcern
private
Get the write concern to use for an operation on this collection, given a session.
Methods included from Helpers
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.
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, = {}) 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) =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
#database ⇒ Mongo::Database (readonly)
Returns The database the collection resides in.
46 47 48 |
# File 'lib/mongo/collection.rb', line 46 def database @database end |
#name ⇒ String (readonly)
Returns The name of the collection.
49 50 51 |
# File 'lib/mongo/collection.rb', line 49 def name @name end |
#options ⇒ Hash (readonly)
Returns The collection options.
52 53 54 |
# File 'lib/mongo/collection.rb', line 52 def @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.
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 && == other. end |
#aggregate(pipeline, options = {}) ⇒ View::Aggregation
Perform an aggregation on the collection.
568 569 570 |
# File 'lib/mongo/collection.rb', line 568 def aggregate(pipeline, = {}) View.new(self, {}, ).aggregate(pipeline, ) end |
#bulk_write(requests, options = {}) ⇒ BulkWrite::Result
Execute a batch of bulk write operations.
942 943 944 |
# File 'lib/mongo/collection.rb', line 942 def bulk_write(requests, = {}) BulkWrite.new(self, requests, ).execute end |
#capped? ⇒ true | false
Is the collection capped?
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
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.
685 686 687 |
# File 'lib/mongo/collection.rb', line 685 def count(filter = nil, = {}) View.new(self, filter || {}, ).count() 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.
719 720 721 |
# File 'lib/mongo/collection.rb', line 719 def count_documents(filter = {}, = {}) View.new(self, filter, ).count_documents() end |
#create(opts = {}) ⇒ Result
Force the collection to be created in the database.
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. = 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| if .key?(ruby_key) [server_key] = .delete(ruby_key) end 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 ) 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: [:collation] || ['collation'], encrypted_fields: encrypted_fields, validator: [:validator], ).execute( next_primary(nil, session), context: context ) end end end |
#delete_many(filter = nil, options = {}) ⇒ Result
Remove documents from the collection.
994 995 996 |
# File 'lib/mongo/collection.rb', line 994 def delete_many(filter = nil, = {}) find(filter, ).delete_many() end |
#delete_one(filter = nil, options = {}) ⇒ Result
Remove a document from the collection.
968 969 970 |
# File 'lib/mongo/collection.rb', line 968 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.
771 772 773 |
# File 'lib/mongo/collection.rb', line 771 def distinct(field_name, filter = nil, = {}) View.new(self, filter || {}, ).distinct(field_name, ) end |
#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.
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.
744 745 746 |
# File 'lib/mongo/collection.rb', line 744 def estimated_document_count( = {}) View.new(self, {}, ).estimated_document_count() end |
#find(filter = nil, options = {}) ⇒ CollectionView
Find documents in the collection.
532 533 534 |
# File 'lib/mongo/collection.rb', line 532 def find(filter = nil, = {}) View.new(self, filter || {}, ) 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.
1157 1158 1159 |
# File 'lib/mongo/collection.rb', line 1157 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.
1243 1244 1245 |
# File 'lib/mongo/collection.rb', line 1243 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.
1201 1202 1203 |
# File 'lib/mongo/collection.rb', line 1201 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.
788 789 790 |
# File 'lib/mongo/collection.rb', line 788 def indexes( = {}) Index::View.new(self, ) end |
#insert_many(documents, options = {}) ⇒ Result
Insert the provided documents into the collection.
910 911 912 913 914 915 |
# File 'lib/mongo/collection.rb', line 910 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.
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.[:id_generator], :session => session, :txn_num => txn_num, :comment => opts[:comment] ).execute_with_connection(connection, context: context) end end end |
#inspect ⇒ String
Get a pretty printed string inspection for the collection.
822 823 824 |
# File 'lib/mongo/collection.rb', line 822 def inspect "#<Mongo::Collection:0x#{object_id} namespace=#{namespace}>" end |
#namespace ⇒ String
Get the fully qualified namespace of the collection.
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).
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.
1025 1026 1027 |
# File 'lib/mongo/collection.rb', line 1025 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.
193 194 195 |
# File 'lib/mongo/collection.rb', line 193 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.
221 222 223 |
# File 'lib/mongo/collection.rb', line 221 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.
1056 1057 1058 |
# File 'lib/mongo/collection.rb', line 1056 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.
810 811 812 |
# File 'lib/mongo/collection.rb', line 810 def search_indexes( = {}) SearchIndex::View.new(self, ) end |
#server_selector ⇒ Mongo::ServerSelector
Get the server selector for this collection.
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.
1264 1265 1266 |
# File 'lib/mongo/collection.rb', line 1264 def system_collection? name.start_with?('system.') end |
#timeout_ms ⇒ Integer | 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.
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.
1089 1090 1091 |
# File 'lib/mongo/collection.rb', line 1089 def update_many(filter, update, = {}) find(filter, ).update_many(update, ) end |
#update_one(filter, update, options = {}) ⇒ Result
Update a single document in the collection.
1122 1123 1124 |
# File 'lib/mongo/collection.rb', line 1122 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.
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.
646 647 648 649 650 |
# File 'lib/mongo/collection.rb', line 646 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) ⇒ Mongo::Collection
Returns A new collection instance.
299 300 301 302 303 304 305 306 307 308 309 310 311 |
# 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 if [:write] && [:write_concern] .delete(:write) end if [:write_concern] && [:write] .delete(:write_concern) end 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.
237 238 239 240 |
# File 'lib/mongo/collection.rb', line 237 def write_concern @write_concern ||= WriteConcern.get( [:write_concern] || [: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.
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..dup opts.delete(:w) return WriteConcern.get(opts) end end wc end |