Class: Mongo::Collection
- Inherits:
-
Object
- Object
- Mongo::Collection
- Extended by:
- Forwardable
- Includes:
- Retryable
- Defined in:
- build/ruby-driver-v2.17/lib/mongo/collection.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/iterable.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/readable.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/writable.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/immutable.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/map_reduce.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/aggregation.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/explainable.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/change_stream.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/builder/map_reduce.rb,
build/ruby-driver-v2.17/lib/mongo/collection/view/builder/aggregation.rb,
build/ruby-driver-v2.17/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
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
- TIME_SERIES_OPTIONS =
Options that can be used for creating a time-series collection.
{ :time_series => :timeseries, :expire_after => :expireAfterSeconds }
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 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.
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 103 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.
42 43 44 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 42 def database @database end |
#name ⇒ String (readonly)
Returns The name of the collection.
45 46 47 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 45 def name @name end |
#options ⇒ Hash (readonly)
Returns The collection options.
48 49 50 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 48 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.
78 79 80 81 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 78 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.
404 405 406 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 404 def aggregate(pipeline, = {}) View.new(self, {}, ).aggregate(pipeline, ) end |
#bulk_write(requests, options = {}) ⇒ BulkWrite::Result
Execute a batch of bulk write operations.
657 658 659 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 657 def bulk_write(requests, = {}) BulkWrite.new(self, requests, ).execute end |
#capped? ⇒ true, false
Is the collection capped?
228 229 230 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 228 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.
473 474 475 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 473 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.
500 501 502 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 500 def count_documents(filter = {}, = {}) View.new(self, filter, ).count_documents() end |
#create(opts = {}) ⇒ Result
Force the collection to be created in the database.
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 248 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(*TIME_SERIES_OPTIONS.keys)) # Converting Ruby spelled time series options to server style. TIME_SERIES_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::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'], ).execute(next_primary(nil, session), context: context) end end |
#delete_many(filter = nil, options = {}) ⇒ Result
Remove documents from the collection.
701 702 703 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 701 def delete_many(filter = nil, = {}) find(filter, ).delete_many() end |
#delete_one(filter = nil, options = {}) ⇒ Result
Remove a document from the collection.
679 680 681 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 679 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.
540 541 542 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 540 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.
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 302 def drop(opts = {}) client.send(:with_session, opts) do |session| temp_write_concern = write_concern write_concern = if opts[:write_concern] WriteConcern.get(opts[:write_concern]) else temp_write_concern end Operation::Drop.new({ selector: { :drop => name }, db_name: database.name, write_concern: write_concern, session: session, }).execute(next_primary(nil, session), context: Operation::Context.new(client: client, session: session)) end rescue Error::OperationFailure => ex # NamespaceNotFound if ex.code == 26 || ex.code.nil? && ex. =~ /ns not found/ false else raise 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.
519 520 521 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 519 def estimated_document_count( = {}) View.new(self, {}, ).estimated_document_count() end |
#find(filter = nil, options = {}) ⇒ CollectionView
Find documents in the collection.
370 371 372 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 370 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.
839 840 841 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 839 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.
917 918 919 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 917 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.
879 880 881 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 879 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.
557 558 559 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 557 def indexes( = {}) Index::View.new(self, ) end |
#insert_many(documents, options = {}) ⇒ Result
Insert the provided documents into the collection.
631 632 633 634 635 636 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 631 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.
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 586 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 write_with_retry(session, write_concern) do |server, txn_num| 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, ).execute(server, context: Operation::Context.new(client: client, session: session)) end end end |
#inspect ⇒ String
Get a pretty printed string inspection for the collection.
569 570 571 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 569 def inspect "#<Mongo::Collection:0x#{object_id} namespace=#{namespace}>" end |
#namespace ⇒ String
Get the fully qualified namespace of the collection.
929 930 931 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 929 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.
724 725 726 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 724 def parallel_scan(cursor_count, = {}) find({}, ).send(:parallel_scan, cursor_count, ) end |
#read_concern ⇒ Hash
Get the read concern for this collection instance.
129 130 131 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 129 def read_concern [:read_concern] || database.read_concern end |
#read_preference ⇒ Hash
Get the read preference on this collection.
153 154 155 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 153 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.
751 752 753 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 751 def replace_one(filter, replacement, = {}) find(filter, ).replace_one(replacement, ) end |
#server_selector ⇒ Mongo::ServerSelector
Get the server selector on this collection.
141 142 143 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 141 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.
938 939 940 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 938 def system_collection? name.start_with?('system.') end |
#update_many(filter, update, options = {}) ⇒ Result
Update documents in the collection.
780 781 782 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 780 def update_many(filter, update, = {}) find(filter, ).update_many(update, ) end |
#update_one(filter, update, options = {}) ⇒ Result
Update a single document in the collection.
809 810 811 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 809 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.
444 445 446 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 444 def watch(pipeline = [], = {}) View::ChangeStream.new(View.new(self, {}, ), pipeline, nil, ) end |
#with(new_options) ⇒ Mongo::Collection
Returns A new collection instance.
206 207 208 209 210 211 212 213 214 215 216 217 218 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 206 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 write concern on this collection.
165 166 167 168 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 165 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.
180 181 182 183 184 185 186 187 188 189 190 |
# File 'build/ruby-driver-v2.17/lib/mongo/collection.rb', line 180 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 |