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/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 }
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 = {}) ⇒ 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 read concern for this collection instance.
-
#read_preference ⇒ Hash
Get the read preference on 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 on 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 write concern on this collection.
-
#write_concern_with_session(session) ⇒ Mongo::WriteConcern
private
Get the write concern for the collection, given the session.
Methods included from Helpers
Methods included from QueryableEncryption
#maybe_create_qe_collections, #maybe_drop_emm_collections
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.
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
# File 'lib/mongo/collection.rb', line 118 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: #{options.inspect}" end @database = database @name = name.to_s.freeze = .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 .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 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 = {}) ⇒ Aggregation
Perform an aggregation on the collection.
428 429 430 |
# File 'lib/mongo/collection.rb', line 428 def aggregate(pipeline, = {}) View.new(self, {}, ).aggregate(pipeline, ) end |
#bulk_write(requests, options = {}) ⇒ BulkWrite::Result
Execute a batch of bulk write operations.
725 726 727 |
# File 'lib/mongo/collection.rb', line 725 def bulk_write(requests, = {}) BulkWrite.new(self, requests, ).execute end |
#capped? ⇒ true, false
Is the collection capped?
243 244 245 |
# File 'lib/mongo/collection.rb', line 243 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.
532 533 534 |
# File 'lib/mongo/collection.rb', line 532 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.
562 563 564 |
# File 'lib/mongo/collection.rb', line 562 def count_documents(filter = {}, = {}) View.new(self, filter, ).count_documents() end |
#create(opts = {}) ⇒ Result
Force the collection to be created in the database.
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
# File 'lib/mongo/collection.rb', line 269 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. = Hash[self..reject do |key, value| %w(read read_preference read_concern).include?(key.to_s) end] .update(opts.slice(*CREATE_COLLECTION_OPTIONS.keys)) # 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.
769 770 771 |
# File 'lib/mongo/collection.rb', line 769 def delete_many(filter = nil, = {}) find(filter, ).delete_many() end |
#delete_one(filter = nil, options = {}) ⇒ Result
Remove a document from the collection.
747 748 749 |
# File 'lib/mongo/collection.rb', line 747 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.
604 605 606 |
# File 'lib/mongo/collection.rb', line 604 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.
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/mongo/collection.rb', line 327 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.
583 584 585 |
# File 'lib/mongo/collection.rb', line 583 def estimated_document_count( = {}) View.new(self, {}, ).estimated_document_count() end |
#find(filter = nil, options = {}) ⇒ CollectionView
Find documents in the collection.
393 394 395 |
# File 'lib/mongo/collection.rb', line 393 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.
907 908 909 |
# File 'lib/mongo/collection.rb', line 907 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.
985 986 987 |
# File 'lib/mongo/collection.rb', line 985 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.
947 948 949 |
# File 'lib/mongo/collection.rb', line 947 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.
621 622 623 |
# File 'lib/mongo/collection.rb', line 621 def indexes( = {}) Index::View.new(self, ) end |
#insert_many(documents, options = {}) ⇒ Result
Insert the provided documents into the collection.
697 698 699 700 701 702 |
# File 'lib/mongo/collection.rb', line 697 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.
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 |
# File 'lib/mongo/collection.rb', line 650 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.
633 634 635 |
# File 'lib/mongo/collection.rb', line 633 def inspect "#<Mongo::Collection:0x#{object_id} namespace=#{namespace}>" end |
#namespace ⇒ String
Get the fully qualified namespace of the collection.
997 998 999 |
# File 'lib/mongo/collection.rb', line 997 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.
792 793 794 |
# File 'lib/mongo/collection.rb', line 792 def parallel_scan(cursor_count, = {}) find({}, ).send(:parallel_scan, cursor_count, ) end |
#read_concern ⇒ Hash
Get the read concern for this collection instance.
144 145 146 |
# File 'lib/mongo/collection.rb', line 144 def read_concern [:read_concern] || database.read_concern end |
#read_preference ⇒ Hash
Get the read preference on this collection.
168 169 170 |
# File 'lib/mongo/collection.rb', line 168 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.
819 820 821 |
# File 'lib/mongo/collection.rb', line 819 def replace_one(filter, replacement, = {}) find(filter, ).replace_one(replacement, ) end |
#server_selector ⇒ Mongo::ServerSelector
Get the server selector on this collection.
156 157 158 |
# File 'lib/mongo/collection.rb', line 156 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.
1006 1007 1008 |
# File 'lib/mongo/collection.rb', line 1006 def system_collection? name.start_with?('system.') end |
#update_many(filter, update, options = {}) ⇒ Result
Update documents in the collection.
848 849 850 |
# File 'lib/mongo/collection.rb', line 848 def update_many(filter, update, = {}) find(filter, ).update_many(update, ) end |
#update_one(filter, update, options = {}) ⇒ Result
Update a single document in the collection.
877 878 879 |
# File 'lib/mongo/collection.rb', line 877 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.
499 500 501 502 503 |
# File 'lib/mongo/collection.rb', line 499 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.
221 222 223 224 225 226 227 228 229 230 231 232 233 |
# File 'lib/mongo/collection.rb', line 221 def with() .keys.each do |k| raise Error::UnchangeableCollectionOption.new(k) unless CHANGEABLE_OPTIONS.include?(k) end = .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 write concern on this collection.
180 181 182 183 |
# File 'lib/mongo/collection.rb', line 180 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 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.
195 196 197 198 199 200 201 202 203 204 205 |
# File 'lib/mongo/collection.rb', line 195 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 |