Class: Mongo::Collection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Retryable
Defined in:
lib/mongo/collection.rb,
lib/mongo/collection/view.rb,
lib/mongo/collection/view/readable.rb,
lib/mongo/collection/view/writable.rb,
lib/mongo/collection/view/iterable.rb,
lib/mongo/collection/view/immutable.rb,
lib/mongo/collection/view/map_reduce.rb,
lib/mongo/collection/view/explainable.rb,
lib/mongo/collection/view/aggregation.rb,
lib/mongo/collection/view/builder/flags.rb,
lib/mongo/collection/view/builder/op_query.rb,
lib/mongo/collection/view/builder/modifiers.rb,
lib/mongo/collection/view/builder/map_reduce.rb,
lib/mongo/collection/view/builder/aggregation.rb,
lib/mongo/collection/view/builder/find_command.rb

Overview

Represents a collection in the database and operations that can directly be applied to one.

Since:

  • 2.0.0

Defined Under Namespace

Classes: View

Constant Summary

CAPPED =

The capped option.

Since:

  • 2.1.0

'capped'.freeze
NS =

The ns field constant.

Since:

  • 2.1.0

'ns'.freeze
CHANGEABLE_OPTIONS =

Options that can be updated on a new Collection instance via the #with method.

Since:

  • 2.1.0

[ :read, :read_concern, :write ].freeze

Constants included from Retryable

Retryable::COULD_NOT_CONTACT_PRIMARY, Retryable::NOT_MASTER

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Retryable

#read_with_one_retry, #read_with_retry, #write_with_retry

Constructor Details

#initialize(database, name, options = {}) ⇒ Collection

Instantiate a new collection.

Examples:

Instantiate a new collection.

Mongo::Collection.new(database, 'test')

Parameters:

  • database (Mongo::Database)

    The collection's database.

  • name (String, Symbol)

    The collection name.

  • options (Hash) (defaults to: {})

    The collection options.

Raises:

Since:

  • 2.0.0



87
88
89
90
91
92
# File 'lib/mongo/collection.rb', line 87

def initialize(database, name, options = {})
  raise Error::InvalidCollectionName.new unless name
  @database = database
  @name = name.to_s.freeze
  @options = options.freeze
end

Instance Attribute Details

#databaseMongo::Database (readonly)

Returns The database the collection resides in.

Returns:

Since:

  • 2.0.0



39
40
41
# File 'lib/mongo/collection.rb', line 39

def database
  @database
end

#nameString (readonly)

Returns The name of the collection.

Returns:

  • (String)

    The name of the collection.

Since:

  • 2.0.0



42
43
44
# File 'lib/mongo/collection.rb', line 42

def name
  @name
end

#optionsHash (readonly)

Returns The collection options.

Returns:

  • (Hash)

    The collection options.

Since:

  • 2.0.0



45
46
47
# File 'lib/mongo/collection.rb', line 45

def options
  @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.

Examples:

Check collection equality.

collection == other

Parameters:

  • other (Object)

    The object to check.

Returns:

  • (true, false)

    If the objects are equal.

Since:

  • 2.0.0



72
73
74
75
# File 'lib/mongo/collection.rb', line 72

def ==(other)
  return false unless other.is_a?(Collection)
  name == other.name && database == other.database && options == other.options
end

#aggregate(pipeline, options = {}) ⇒ Aggregation

Perform an aggregation on the collection.

Examples:

Perform an aggregation.

collection.aggregate([ { "$group" => { "_id" => "$city", "tpop" => { "$sum" => "$pop" }}} ])

Parameters:

  • pipeline (Array<Hash>)

    The aggregation pipeline.

  • options (Hash) (defaults to: {})

    The aggregation options.

Options Hash (options):

  • :allow_disk_use (true, false)

    Set to true if disk usage is allowed during the aggregation.

  • :batch_size (Integer)

    The number of documents to return per batch.

  • :max_time_ms (Integer)

    The maximum amount of time in milliseconds to allow the aggregation to run.

  • :use_cursor (true, false)

    Indicates whether the command will request that the server provide results using a cursor.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

Returns:

  • (Aggregation)

    The aggregation object.

Since:

  • 2.1.0



271
272
273
# File 'lib/mongo/collection.rb', line 271

def aggregate(pipeline, options = {})
  View.new(self, {}).aggregate(pipeline, options)
end

#bulk_write(requests, options = {}) ⇒ BulkWrite::Result

Execute a batch of bulk write operations.

Examples:

Execute a bulk write.

collection.bulk_write(operations, options)

Parameters:

  • requests (Array<Hash>)

    The bulk write requests.

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :ordered (true, false)

    Whether the operations should be executed in order.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer, :fsync => Boolean, :j => Boolean.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

Returns:

Since:

  • 2.0.0



403
404
405
# File 'lib/mongo/collection.rb', line 403

def bulk_write(requests, options = {})
  BulkWrite.new(self, requests, options).execute
end

#capped?true, false

Is the collection capped?

Examples:

Is the collection capped?

collection.capped?

Returns:

  • (true, false)

    If the collection is capped.

Since:

  • 2.0.0



159
160
161
# File 'lib/mongo/collection.rb', line 159

def capped?
  database.command(:collstats => name).documents[0][CAPPED]
end

#count(filter = nil, options = {}) ⇒ Integer

Get a count of matching documents in the collection.

Examples:

Get the count.

collection.count(name: 1)

Parameters:

  • filter (Hash) (defaults to: nil)

    A filter for matching documents.

  • options (Hash) (defaults to: {})

    The count options.

Options Hash (options):

  • :hint (Hash)

    The index to use.

  • :limit (Integer)

    The maximum number of documents to count.

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run.

  • :skip (Integer)

    The number of documents to skip before counting.

  • :read (Hash)

    The read preference options.

  • :collation (Hash)

    The collation to use.

Returns:

  • (Integer)

    The document count.

Since:

  • 2.1.0



293
294
295
# File 'lib/mongo/collection.rb', line 293

def count(filter = nil, options = {})
  View.new(self, filter || {}).count(options)
end

#createResult

Force the collection to be created in the database.

Examples:

Force the collection to be created.

collection.create

Returns:

  • (Result)

    The result of the command.

Since:

  • 2.0.0



171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/mongo/collection.rb', line 171

def create
  operation = { :create => name }.merge(options)
  operation.delete(:write)
  server = next_primary
  if (options[:collation] || options[Operation::COLLATION]) && !server.features.collation_enabled?
    raise Error::UnsupportedCollation.new
  end
  Operation::Commands::Create.new({
                                    selector: operation,
                                    db_name: database.name,
                                    write_concern: write_concern
                                  }).execute(server)
end

#delete_many(filter = nil, options = {}) ⇒ Result

Remove documents from the collection.

Examples:

Remove multiple documents from the collection.

collection.delete_many

Parameters:

  • filter (Hash) (defaults to: nil)

    The filter to use.

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :collation (Hash)

    The collation to use.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



437
438
439
# File 'lib/mongo/collection.rb', line 437

def delete_many(filter = nil, options = {})
  find(filter).delete_many(options)
end

#delete_one(filter = nil, options = {}) ⇒ Result

Remove a document from the collection.

Examples:

Remove a single document from the collection.

collection.delete_one

Parameters:

  • filter (Hash) (defaults to: nil)

    The filter to use.

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :collation (Hash)

    The collation to use.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



420
421
422
# File 'lib/mongo/collection.rb', line 420

def delete_one(filter = nil, options = {})
  find(filter).delete_one(options)
end

#distinct(field_name, filter = nil, options = {}) ⇒ Array<Object>

Get a list of distinct values for a specific field.

Examples:

Get the distinct values.

collection.distinct('name')

Parameters:

  • field_name (Symbol, String)

    The name of the field.

  • filter (Hash) (defaults to: nil)

    The documents from which to retrieve the distinct values.

  • options (Hash) (defaults to: {})

    The distinct command options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run.

  • :read (Hash)

    The read preference options.

  • :collation (Hash)

    The collation to use.

Returns:

  • (Array<Object>)

    The list of distinct values.

Since:

  • 2.1.0



313
314
315
# File 'lib/mongo/collection.rb', line 313

def distinct(field_name, filter = nil, options = {})
  View.new(self, filter || {}).distinct(field_name, options)
end

#dropResult

Note:

An error returned if the collection doesn't exist is suppressed.

Drop the collection. Will also drop all indexes associated with the collection.

Examples:

Drop the collection.

collection.drop

Returns:

  • (Result)

    The result of the command.

Since:

  • 2.0.0



196
197
198
199
200
201
202
203
204
205
206
# File 'lib/mongo/collection.rb', line 196

def drop
  Operation::Commands::Drop.new({
                                  selector: { :drop => name },
                                  db_name: database.name,
                                  write_concern: write_concern
                                }).execute(next_primary)

rescue Error::OperationFailure => ex
  raise ex unless ex.message =~ /ns not found/
  false
end

#find(filter = nil, options = {}) ⇒ CollectionView

Find documents in the collection.

Examples:

Find documents in the collection by a selector.

collection.find(name: 1)

Get all documents in a collection.

collection.find

Parameters:

  • filter (Hash) (defaults to: nil)

    The filter to use in the find.

  • options (Hash) (defaults to: {})

    The options for the find.

Options Hash (options):

  • :allow_partial_results (true, false)

    Allows the query to get partial results if some shards are down.

  • :batch_size (Integer)

    The number of documents returned in each batch of results from MongoDB.

  • :comment (String)

    Associate a comment with the query.

  • :cursor_type (:tailable, :tailable_await)

    The type of cursor to use.

  • :limit (Integer)

    The max number of docs to return from the query.

  • :max_time_ms (Integer)

    The maximum amount of time to allow the query to run in milliseconds.

  • :modifiers (Hash)

    A document containing meta-operators modifying the output or behavior of a query.

  • :no_cursor_timeout (true, false)

    The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that.

  • :oplog_replay (true, false)

    Internal replication use only - driver should not set.

  • :projection (Hash)

    The fields to include or exclude from each doc in the result set.

  • :skip (Integer)

    The number of docs to skip before returning results.

  • :sort (Hash)

    The key and direction pairs by which the result set will be sorted.

  • :collation (Hash)

    The collation to use.

Returns:

  • (CollectionView)

    The collection view.

Since:

  • 2.0.0



245
246
247
# File 'lib/mongo/collection.rb', line 245

def find(filter = nil, options = {})
  View.new(self, filter || {}, options)
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.

Examples:

Find one document and delete it.

collection.find_one_and_delete(name: 'test')

Parameters:

  • filter (Hash)

    The filter to use.

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run in milliseconds.

  • :projection (Hash)

    The fields to include or exclude in the returned doc.

  • :sort (Hash)

    The key and direction pairs by which the result set will be sorted.

  • :write_concern (Hash)

    The write concern options. Defaults to the collection's write concern.

  • :collation (Hash)

    The collation to use.

Returns:

  • (BSON::Document, nil)

    The document, if found.

Since:

  • 2.1.0



550
551
552
# File 'lib/mongo/collection.rb', line 550

def find_one_and_delete(filter, options = {})
  find(filter, options).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.

Examples:

Find a document and replace it, returning the original.

collection.find_one_and_replace({ name: 'test' }, { name: 'test1' })

Find a document and replace it, returning the new document.

collection.find_one_and_replace({ name: 'test' }, { name: 'test1' }, :return_document => :after)

Parameters:

  • filter (Hash)

    The filter to use.

  • replacement (BSON::Document)

    The replacement document.

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run in milliseconds.

  • :projection (Hash)

    The fields to include or exclude in the returned doc.

  • :sort (Hash)

    The key and direction pairs by which the result set will be sorted.

  • :return_document (Symbol)

    Either :before or :after.

  • :upsert (true, false)

    Whether to upsert if the document doesn't exist.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

  • :write_concern (Hash)

    The write concern options. Defaults to the collection's write concern.

  • :collation (Hash)

    The collation to use.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



616
617
618
# File 'lib/mongo/collection.rb', line 616

def find_one_and_replace(filter, replacement, options = {})
  find(filter, options).find_one_and_update(replacement, options)
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.

Examples:

Find a document and update it, returning the original.

collection.find_one_and_update({ name: 'test' }, { "$set" => { name: 'test1' }})

Find a document and update it, returning the updated document.

collection.find_one_and_update({ name: 'test' }, { "$set" => { name: 'test1' }}, :return_document => :after)

Parameters:

  • filter (Hash)

    The filter to use.

  • update (BSON::Document)

    The update statement.

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run in milliseconds.

  • :projection (Hash)

    The fields to include or exclude in the returned doc.

  • :sort (Hash)

    The key and direction pairs by which the result set will be sorted.

  • :return_document (Symbol)

    Either :before or :after.

  • :upsert (true, false)

    Whether to upsert if the document doesn't exist.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

  • :write_concern (Hash)

    The write concern options. Defaults to the collection's write concern.

  • :collation (Hash)

    The collation to use.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



583
584
585
# File 'lib/mongo/collection.rb', line 583

def find_one_and_update(filter, update, options = {})
  find(filter, options).find_one_and_update(update, options)
end

#indexes(options = {}) ⇒ View::Index

Get a view of all indexes for this collection. Can be iterated or has more operations.

Examples:

Get the index view.

collection.indexes

Parameters:

  • options (Hash) (defaults to: {})

    Options for getting a list of all indexes.

Returns:

  • (View::Index)

    The index view.

Since:

  • 2.0.0



328
329
330
# File 'lib/mongo/collection.rb', line 328

def indexes(options = {})
  Index::View.new(self, options)
end

#insert_many(documents, options = {}) ⇒ Result

Insert the provided documents into the collection.

Examples:

Insert documents into the collection.

collection.insert_many([{ name: 'test' }])

Parameters:

  • documents (Array<Hash>)

    The documents to insert.

  • options (Hash) (defaults to: {})

    The insert options.

Returns:

  • (Result)

    The database response wrapper.

Since:

  • 2.0.0



380
381
382
383
# File 'lib/mongo/collection.rb', line 380

def insert_many(documents, options = {})
  inserts = documents.map{ |doc| { :insert_one => doc }}
  bulk_write(inserts, options)
end

#insert_one(document, options = {}) ⇒ Result

Insert a single document into the collection.

Examples:

Insert a document into the collection.

collection.insert_one({ name: 'test' })

Parameters:

  • document (Hash)

    The document to insert.

  • options (Hash) (defaults to: {})

    The insert options.

Returns:

  • (Result)

    The database response wrapper.

Since:

  • 2.0.0



355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/mongo/collection.rb', line 355

def insert_one(document, options = {})
  write_with_retry do
    Operation::Write::Insert.new(
      :documents => [ document ],
      :db_name => database.name,
      :coll_name => name,
      :write_concern => write_concern,
      :bypass_document_validation => !!options[:bypass_document_validation],
      :options => options,
      :id_generator => client.options[:id_generator]
    ).execute(next_primary)
  end
end

#inspectString

Get a pretty printed string inspection for the collection.

Examples:

Inspect the collection.

collection.inspect

Returns:

  • (String)

    The collection inspection.

Since:

  • 2.0.0



340
341
342
# File 'lib/mongo/collection.rb', line 340

def inspect
  "#<Mongo::Collection:0x#{object_id} namespace=#{namespace}>"
end

#namespaceString

Get the fully qualified namespace of the collection.

Examples:

Get the fully qualified namespace.

collection.namespace

Returns:

  • (String)

    The collection namespace.

Since:

  • 2.0.0



628
629
630
# File 'lib/mongo/collection.rb', line 628

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.

Examples:

Execute a parallel collection scan.

collection.parallel_scan(2)

Parameters:

  • cursor_count (Integer)

    The max number of cursors to return.

  • options (Hash) (defaults to: {})

    The parallel scan command options.

Options Hash (options):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run in milliseconds.

Returns:

  • (Array<Cursor>)

    An array of cursors.

Since:

  • 2.1



459
460
461
# File 'lib/mongo/collection.rb', line 459

def parallel_scan(cursor_count, options = {})
  find.send(:parallel_scan, cursor_count, options)
end

#read_concernHash

Get the read concern for this collection instance.

Examples:

Get the read concern.

collection.read_concern

Returns:

  • (Hash)

    The read concern.

Since:

  • 2.2.0



102
103
104
# File 'lib/mongo/collection.rb', line 102

def read_concern
  @read_concern ||= options[:read_concern]
end

#read_preferenceMongo::ServerSelector

Get the read preference on this collection.

Examples:

Get the read preference.

collection.read_preference

Returns:

Since:

  • 2.0.0



114
115
116
# File 'lib/mongo/collection.rb', line 114

def read_preference
  @read_preference ||= ServerSelector.get(options[:read] || database.read_preference)
end

#replace_one(filter, replacement, options = {}) ⇒ Result

Replaces a single document in the collection with the new document.

Examples:

Replace a single document.

collection.replace_one({ name: 'test' }, { name: 'test1' })

Parameters:

  • filter (Hash)

    The filter to use.

  • replacement (Hash)

    The replacement document..

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :upsert (true, false)

    Whether to upsert if the document doesn't exist.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



481
482
483
# File 'lib/mongo/collection.rb', line 481

def replace_one(filter, replacement, options = {})
  find(filter).replace_one(replacement, options)
end

#update_many(filter, update, options = {}) ⇒ Result

Update documents in the collection.

Examples:

Update multiple documents in the collection.

collection.update_many({ name: 'test'}, '$set' => { name: 'test1' })

Parameters:

  • filter (Hash)

    The filter to use.

  • update (Hash)

    The update statement.

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :upsert (true, false)

    Whether to upsert if the document doesn't exist.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



503
504
505
# File 'lib/mongo/collection.rb', line 503

def update_many(filter, update, options = {})
  find(filter).update_many(update, options)
end

#update_one(filter, update, options = {}) ⇒ Result

Update a single document in the collection.

Examples:

Update a single document in the collection.

collection.update_one({ name: 'test'}, '$set' => { name: 'test1'})

Parameters:

  • filter (Hash)

    The filter to use.

  • update (Hash)

    The update statement.

  • options (Hash) (defaults to: {})

    The options.

Options Hash (options):

  • :upsert (true, false)

    Whether to upsert if the document doesn't exist.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



525
526
527
# File 'lib/mongo/collection.rb', line 525

def update_one(filter, update, options = {})
  find(filter).update_one(update, options)
end

#with(new_options) ⇒ Mongo::Collection

Returns A new collection instance.

Parameters:

  • new_options (Hash)

    The new options to use.

Returns:

Since:

  • 2.1.0



144
145
146
147
148
149
# File 'lib/mongo/collection.rb', line 144

def with(new_options)
  new_options.keys.each do |k|
    raise Error::UnchangeableCollectionOption.new(k) unless CHANGEABLE_OPTIONS.include?(k)
  end
  Collection.new(database, name, options.merge(new_options))
end

#write_concernMongo::WriteConcern

Get the write concern on this collection.

Examples:

Get the write concern.

collection.write_concern

Returns:

Since:

  • 2.0.0



126
127
128
# File 'lib/mongo/collection.rb', line 126

def write_concern
  @write_concern ||= WriteConcern.get(options[:write] || database.write_concern)
end