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/writable.rb,
lib/mongo/collection/view/readable.rb,
lib/mongo/collection/view/iterable.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/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:

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

- (Collection) initialize(database, name, options = {})

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

- (Mongo::Database) 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

- (String) name (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

- (Hash) options (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

- (true, false) ==(other)

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

- (Aggregation) aggregate(pipeline, options = {})

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.

Returns:

  • (Aggregation)

    The aggregation object.

Since:

  • 2.1.0



256
257
258
# File 'lib/mongo/collection.rb', line 256

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

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

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



384
385
386
# File 'lib/mongo/collection.rb', line 384

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

- (true, false) capped?

Is the collection capped?

Examples:

Is the collection capped?

collection.capped?

Returns:

  • (true, false)

    If the collection is capped.

Since:

  • 2.0.0



161
162
163
# File 'lib/mongo/collection.rb', line 161

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

- (Integer) count(filter = nil, options = {})

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.

Returns:

  • (Integer)

    The document count.

Since:

  • 2.1.0



276
277
278
# File 'lib/mongo/collection.rb', line 276

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

- (Result) create

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



173
174
175
# File 'lib/mongo/collection.rb', line 173

def create
  database.command({ :create => name }.merge(options))
end

- (Result) delete_many(filter = nil)

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



412
413
414
# File 'lib/mongo/collection.rb', line 412

def delete_many(filter = nil)
  find(filter).delete_many
end

- (Result) delete_one(filter = nil)

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



398
399
400
# File 'lib/mongo/collection.rb', line 398

def delete_one(filter = nil)
  find(filter).delete_one
end

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

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.

Returns:

  • (Array<Object>)

    The list of distinct values.

Since:

  • 2.1.0



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

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

- (Result) drop

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



188
189
190
191
192
193
# File 'lib/mongo/collection.rb', line 188

def drop
  database.command(:drop => name)
rescue Error::OperationFailure => ex
  raise ex unless ex.message =~ /ns not found/
  false
end

- (CollectionView) find(filter = nil, options = {})

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.

Returns:

  • (CollectionView)

    The collection view.

Since:

  • 2.0.0



231
232
233
# File 'lib/mongo/collection.rb', line 231

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

- (BSON::Document?) find_one_and_delete(filter, options = {})

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.

Returns:

  • (BSON::Document, nil)

    The document, if found.

Since:

  • 2.1.0



517
518
519
# File 'lib/mongo/collection.rb', line 517

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

- (BSON::Document) find_one_and_replace(filter, replacement, options = {})

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.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



581
582
583
# File 'lib/mongo/collection.rb', line 581

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

- (BSON::Document) find_one_and_update(filter, update, options = {})

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.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



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

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

- (View::Index) indexes(options = {})

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



309
310
311
# File 'lib/mongo/collection.rb', line 309

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

- (Result) insert_many(documents, options = {})

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



361
362
363
364
# File 'lib/mongo/collection.rb', line 361

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

- (Result) insert_one(document, options = {})

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



336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/mongo/collection.rb', line 336

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.context)
  end
end

- (String) inspect

Get a pretty printed string inspection for the collection.

Examples:

Inspect the collection.

collection.inspect

Returns:

  • (String)

    The collection inspection.

Since:

  • 2.0.0



321
322
323
# File 'lib/mongo/collection.rb', line 321

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

- (String) namespace

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



593
594
595
# File 'lib/mongo/collection.rb', line 593

def namespace
  "#{database.name}.#{name}"
end

- (Array<Cursor>) parallel_scan(cursor_count)

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.

Returns:

  • (Array<Cursor>)

    An array of cursors.

Since:

  • 2.1



430
431
432
# File 'lib/mongo/collection.rb', line 430

def parallel_scan(cursor_count)
  find.send(:parallel_scan, cursor_count)
end

- (Hash) read_concern

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

- (Mongo::ServerSelector) read_preference

Get the read preference on this collection.

Examples:

Get the read preference.

collection.read_preference

Returns:

Since:

  • 2.0.0



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

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

- (Result) replace_one(filter, replacement, options = {})

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



451
452
453
# File 'lib/mongo/collection.rb', line 451

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

- (Result) update_many(filter, update, options = {})

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



472
473
474
# File 'lib/mongo/collection.rb', line 472

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

- (Result) update_one(filter, update, options = {})

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



493
494
495
# File 'lib/mongo/collection.rb', line 493

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

- (Mongo::Collection) with(new_options)

Returns A new collection instance.

Parameters:

  • new_options (Hash)

    The new options to use.

Returns:

Since:

  • 2.1.0



146
147
148
149
150
151
# File 'lib/mongo/collection.rb', line 146

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

- (Mongo::WriteConcern) write_concern

Get the write concern on this collection.

Examples:

Get the write concern.

collection.write_concern

Returns:

Since:

  • 2.0.0



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

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