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.
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/mongo/collection.rb', line 164 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.
91 92 93 94 |
# File 'lib/mongo/collection.rb', line 91 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.
575 576 577 |
# File 'lib/mongo/collection.rb', line 575 def aggregate(pipeline, = {}) View.new(self, {}, ).aggregate(pipeline, ) end |
#bulk_write(requests, options = {}) ⇒ BulkWrite::Result
Execute a batch of bulk write operations.
952 953 954 |
# File 'lib/mongo/collection.rb', line 952 def bulk_write(requests, = {}) BulkWrite.new(self, requests, ).execute end |
#capped? ⇒ true | false
Is the collection capped?
323 324 325 326 327 |
# File 'lib/mongo/collection.rb', line 323 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.
692 693 694 |
# File 'lib/mongo/collection.rb', line 692 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.
726 727 728 |
# File 'lib/mongo/collection.rb', line 726 def count_documents(filter = {}, = {}) View.new(self, filter, ).count_documents() end |
#create(opts = {}) ⇒ Result
Force the collection to be created in the database.
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 431 432 433 434 435 |
# File 'lib/mongo/collection.rb', line 384 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 ) 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.
1004 1005 1006 |
# File 'lib/mongo/collection.rb', line 1004 def delete_many(filter = nil, = {}) find(filter, ).delete_many() end |
#delete_one(filter = nil, options = {}) ⇒ Result
Remove a document from the collection.
978 979 980 |
# File 'lib/mongo/collection.rb', line 978 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.
778 779 780 |
# File 'lib/mongo/collection.rb', line 778 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.
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 |
# File 'lib/mongo/collection.rb', line 459 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.
751 752 753 |
# File 'lib/mongo/collection.rb', line 751 def estimated_document_count( = {}) View.new(self, {}, ).estimated_document_count() end |
#find(filter = nil, options = {}) ⇒ CollectionView
Find documents in the collection.
539 540 541 |
# File 'lib/mongo/collection.rb', line 539 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.
1177 1178 1179 |
# File 'lib/mongo/collection.rb', line 1177 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.
1263 1264 1265 |
# File 'lib/mongo/collection.rb', line 1263 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.
1221 1222 1223 |
# File 'lib/mongo/collection.rb', line 1221 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.
795 796 797 |
# File 'lib/mongo/collection.rb', line 795 def indexes( = {}) Index::View.new(self, ) end |
#insert_many(documents, options = {}) ⇒ Result
Insert the provided documents into the collection.
920 921 922 923 924 925 |
# File 'lib/mongo/collection.rb', line 920 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.
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 884 885 886 887 888 889 890 891 892 893 |
# File 'lib/mongo/collection.rb', line 856 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) ) 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.
829 830 831 |
# File 'lib/mongo/collection.rb', line 829 def inspect "#<Mongo::Collection:0x#{object_id} namespace=#{namespace}>" end |
#namespace ⇒ String
Get the fully qualified namespace of the collection.
1275 1276 1277 |
# File 'lib/mongo/collection.rb', line 1275 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).
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 |
# File 'lib/mongo/collection.rb', line 1300 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.
1035 1036 1037 |
# File 'lib/mongo/collection.rb', line 1035 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.
195 196 197 |
# File 'lib/mongo/collection.rb', line 195 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.
223 224 225 |
# File 'lib/mongo/collection.rb', line 223 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.
1071 1072 1073 |
# File 'lib/mongo/collection.rb', line 1071 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.
817 818 819 |
# File 'lib/mongo/collection.rb', line 817 def search_indexes( = {}) SearchIndex::View.new(self, ) end |
#server_selector ⇒ Mongo::ServerSelector
Get the server selector for this collection.
207 208 209 |
# File 'lib/mongo/collection.rb', line 207 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.
1284 1285 1286 |
# File 'lib/mongo/collection.rb', line 1284 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.
1292 1293 1294 |
# File 'lib/mongo/collection.rb', line 1292 def timeout_ms @timeout_ms || database.timeout_ms end |
#update_many(filter, update, options = {}) ⇒ Result
Update documents in the collection.
1104 1105 1106 |
# File 'lib/mongo/collection.rb', line 1104 def update_many(filter, update, = {}) find(filter, ).update_many(update, ) end |
#update_one(filter, update, options = {}) ⇒ Result
Update a single document in the collection.
1142 1143 1144 |
# File 'lib/mongo/collection.rb', line 1142 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.
653 654 655 656 657 |
# File 'lib/mongo/collection.rb', line 653 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.
301 302 303 304 305 306 307 308 309 310 311 312 313 |
# File 'lib/mongo/collection.rb', line 301 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.
239 240 241 242 |
# File 'lib/mongo/collection.rb', line 239 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.
255 256 257 258 259 260 261 262 263 264 265 |
# File 'lib/mongo/collection.rb', line 255 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 |