Class: Mongo::Collection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/mongo/collection.rb,
lib/mongo/collection/view.rb,
lib/mongo/collection/view/iterable.rb,
lib/mongo/collection/view/writable.rb,
lib/mongo/collection/view/readable.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

Overview

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

Since:

Defined Under Namespace

Classes: View

Constant Summary

CHANGEABLE_OPTIONS =

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

Since:

  • 2.1.0

[ :read, :write ]

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

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



76
77
78
79
80
81
# File 'lib/mongo/collection.rb', line 76

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



28
29
30
# File 'lib/mongo/collection.rb', line 28

def database
  @database
end

- (String) name (readonly)

Returns The name of the collection.

Returns:

  • (String)

    The name of the collection.

Since:

  • 2.0.0



31
32
33
# File 'lib/mongo/collection.rb', line 31

def name
  @name
end

- (Hash) options (readonly)

Returns The collection options.

Returns:

  • (Hash)

    The collection options.

Since:

  • 2.0.0



34
35
36
# File 'lib/mongo/collection.rb', line 34

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



61
62
63
64
# File 'lib/mongo/collection.rb', line 61

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.

Returns:

  • (Aggregation)

    The aggregation object.

Since:

  • 2.1.0



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

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.

Returns:

Since:

  • 2.0.0



353
354
355
# File 'lib/mongo/collection.rb', line 353

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



138
139
140
# File 'lib/mongo/collection.rb', line 138

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



251
252
253
# File 'lib/mongo/collection.rb', line 251

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



150
151
152
# File 'lib/mongo/collection.rb', line 150

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



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

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



367
368
369
# File 'lib/mongo/collection.rb', line 367

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



269
270
271
# File 'lib/mongo/collection.rb', line 269

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



165
166
167
168
169
170
# File 'lib/mongo/collection.rb', line 165

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



208
209
210
# File 'lib/mongo/collection.rb', line 208

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.

Returns:

  • (BSON::Document, nil)

    The document, if found.

Since:

  • 2.1.0



478
479
480
# File 'lib/mongo/collection.rb', line 478

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.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



534
535
536
# File 'lib/mongo/collection.rb', line 534

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.

Returns:

  • (BSON::Document)

    The document.

Since:

  • 2.1.0



506
507
508
# File 'lib/mongo/collection.rb', line 506

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



284
285
286
# File 'lib/mongo/collection.rb', line 284

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



332
333
334
335
# File 'lib/mongo/collection.rb', line 332

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



311
312
313
314
315
316
317
318
319
# File 'lib/mongo/collection.rb', line 311

def insert_one(document, options = {})
  Operation::Write::Insert.new(
    :documents => [ document ],
    :db_name => database.name,
    :coll_name => name,
    :write_concern => write_concern,
    :options => options
  ).execute(next_primary.context)
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



296
297
298
# File 'lib/mongo/collection.rb', line 296

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



546
547
548
# File 'lib/mongo/collection.rb', line 546

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



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

def parallel_scan(cursor_count)
  find.send(:parallel_scan, cursor_count)
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



91
92
93
94
# File 'lib/mongo/collection.rb', line 91

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



418
419
420
# File 'lib/mongo/collection.rb', line 418

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



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

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.

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.1.0



456
457
458
# File 'lib/mongo/collection.rb', line 456

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



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

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



104
105
106
107
# File 'lib/mongo/collection.rb', line 104

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