Class: Mongo::Collection
- Inherits:
-
Object
- Object
- Mongo::Collection
- Extended by:
- Forwardable
- Includes:
- Helpers, QueryableEncryption, Retryable
- Defined in:
- build/ruby-driver-v2.19/lib/mongo/collection.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view.rb,
build/ruby-driver-v2.19/lib/mongo/collection/helpers.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/iterable.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/readable.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/writable.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/immutable.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/map_reduce.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/aggregation.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/explainable.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/change_stream.rb,
build/ruby-driver-v2.19/lib/mongo/collection/queryable_encryption.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/builder/map_reduce.rb,
build/ruby-driver-v2.19/lib/mongo/collection/view/builder/aggregation.rb,
build/ruby-driver-v2.19/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 = {}) ⇒ View::Index
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.
-
#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.
-
#server_selector ⇒ Mongo::ServerSelector
Get the server selector for this collection.
-
#system_collection? ⇒ Boolean
private
Whether the collection is a system collection.
-
#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.
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 158 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 =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 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 46 def database @database end |
#name ⇒ String (readonly)
Returns The name of the collection.
49 50 51 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 49 def name @name end |
#options ⇒ Hash (readonly)
Returns The collection options.
52 53 54 |
# File 'build/ruby-driver-v2.19/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 'build/ruby-driver-v2.19/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.
536 537 538 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 536 def aggregate(pipeline, = {}) View.new(self, {}, ).aggregate(pipeline, ) end |
#bulk_write(requests, options = {}) ⇒ BulkWrite::Result
Execute a batch of bulk write operations.
845 846 847 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 845 def bulk_write(requests, = {}) BulkWrite.new(self, requests, ).execute end |
#capped? ⇒ true | false
Is the collection capped?
316 317 318 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 316 def capped? database.read_command(:collstats => name).documents[0][CAPPED] 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.
640 641 642 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 640 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.
670 671 672 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 670 def count_documents(filter = {}, = {}) View.new(self, filter, ).count_documents() end |
#create(opts = {}) ⇒ Result
Force the collection to be created in the database.
373 374 375 376 377 378 379 380 381 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 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 373 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.
889 890 891 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 889 def delete_many(filter = nil, = {}) find(filter, ).delete_many() end |
#delete_one(filter = nil, options = {}) ⇒ Result
Remove a document from the collection.
867 868 869 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 867 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.
712 713 714 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 712 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.
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 435 def drop(opts = {}) client.send(: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 = 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.
691 692 693 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 691 def estimated_document_count( = {}) View.new(self, {}, ).estimated_document_count() end |
#find(filter = nil, options = {}) ⇒ CollectionView
Find documents in the collection.
501 502 503 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 501 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.
1027 1028 1029 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 1027 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.
1105 1106 1107 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 1105 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.
1067 1068 1069 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 1067 def find_one_and_update(filter, update, = {}) find(filter, ).find_one_and_update(update, ) end |
#indexes(options = {}) ⇒ View::Index
Get a view of all indexes for this collection. Can be iterated or has more operations.
729 730 731 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 729 def indexes( = {}) Index::View.new(self, ) end |
#insert_many(documents, options = {}) ⇒ Result
Insert the provided documents into the collection.
817 818 819 820 821 822 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 817 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.
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 764 def insert_one(document, opts = {}) QueryCache.clear_namespace(namespace) client.send(: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) 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.
741 742 743 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 741 def inspect "#<Mongo::Collection:0x#{object_id} namespace=#{namespace}>" end |
#namespace ⇒ String
Get the fully qualified namespace of the collection.
1117 1118 1119 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 1117 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.
912 913 914 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 912 def parallel_scan(cursor_count, = {}) find({}, ).send(: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.
188 189 190 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 188 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.
216 217 218 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 216 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.
939 940 941 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 939 def replace_one(filter, replacement, = {}) find(filter, ).replace_one(replacement, ) end |
#server_selector ⇒ Mongo::ServerSelector
Get the server selector for this collection.
200 201 202 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 200 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.
1126 1127 1128 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 1126 def system_collection? name.start_with?('system.') end |
#update_many(filter, update, options = {}) ⇒ Result
Update documents in the collection.
968 969 970 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 968 def update_many(filter, update, = {}) find(filter, ).update_many(update, ) end |
#update_one(filter, update, options = {}) ⇒ Result
Update a single document in the collection.
997 998 999 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 997 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.
607 608 609 610 611 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 607 def watch(pipeline = [], = {}) = .dup [:await_data] = true if [:max_await_time_ms] View::ChangeStream.new(View.new(self, {}, ), pipeline, nil, ) end |
#with(new_options) ⇒ Mongo::Collection
Returns A new collection instance.
294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 294 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.
232 233 234 235 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 232 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.
248 249 250 251 252 253 254 255 256 257 258 |
# File 'build/ruby-driver-v2.19/lib/mongo/collection.rb', line 248 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 |