NAME

MongoDB::Collection - A MongoDB Collection

VERSION

version v0.999.998.3

SYNOPSIS

# get a Collection via the Database object
$coll = $db->get_collection("people");

# insert a document
$coll->insert_one( { name => "John Doe", age => 42 } );

# insert one or more documents
$coll->insert_many( \@documents );

# delete a document
$coll->delete_one( { name => "John Doe" } );

# update a document
$coll->update_one( { name => "John Doe" }, { '$inc' => { age => 1 } } );

# find a single document
$doc = $coll->find_one( { name => "John Doe" } )

# Get a MongoDB::Cursor for a query
$cursor = $coll->find( { age => 42 } );

# Cursor iteration
while ( my $doc = $cursor->next ) {
    ...
}

DESCRIPTION

This class models a MongoDB collection and provides an API for interacting with it.

Generally, you never construct one of these directly with new. Instead, you call get_collection on a MongoDB::Database object.

USAGE

Error handling

Unless otherwise explictly documented, all methods throw exceptions if an error occurs. The error types are documented in MongoDB::Error.

To catch and handle errors, the Try::Tiny and Safe::Isa modules are recommended:

use Try::Tiny;
use Safe::Isa; # provides $_isa

try {
    $coll->insert( $doc )
}
catch {
    if ( $_->$_isa("MongoDB::DuplicateKeyError" ) {
        ...
    }
    else {
        ...
    }
};

To retry failures automatically, consider using Try::Tiny::Retry.

Terminology

Document

A collection of key-value pairs. A Perl hash is a document. Array references with an even number of elements and Tie::IxHash objects may also be used as documents.

Ordered document

Many MongoDB::Collection method parameters or options require an ordered document: an ordered list of key/value pairs. Perl's hashes are not ordered and since Perl v5.18 are guaranteed to have random order. Therefore, when an ordered document is called for, you may use an array reference of pairs or a Tie::IxHash object. You may use a hash reference if there is only one key/value pair.

Filter expression

A filter expression provides the query criteria to select a document for deletion. It must be an "Ordered document".

ATTRIBUTES

database

The MongoDB::Database representing the database that contains the collection.

name

The name of the collection.

read_preference

A MongoDB::ReadPreference object. It may be initialized with a string corresponding to one of the valid read preference modes or a hash reference that will be coerced into a new MongoDB::ReadPreference object. By default it will be inherited from a MongoDB::Database object.

write_concern

A MongoDB::WriteConcern object. It may be initialized with a hash reference that will be coerced into a new MongoDB::WriteConcern object. By default it will be inherited from a MongoDB::Database object.

METHODS

client

$client = $coll->client;

Returns the MongoDB::MongoClient object associated with this object.

full_name

$full_name = $coll->full_name;

Returns the full name of the collection, including the namespace of the database it's in prefixed with a dot character. E.g. collection "foo" in database "test" would result in a full_name of "test.foo".

clone

$coll2 = $coll1->clone( write_concern => { w => 2 } );

Constructs a copy of the original collection, but allows changing attributes in the copy.

insert_one

$res = $coll->insert_one( $document );

Inserts a single document into the database and returns a MongoDB::InsertOneResult object.If no _id field is present, one will be added to the original document.

insert_many

$res = $coll->insert_many( [ @documents ] );
$res = $coll->insert_many( [ @documents ], { ordered => 0 } );

Inserts each of the documents in an array reference into the database and returns a MongoDB::InsertManyResult. This is syntactic sugar for doing a MongoDB::BulkWrite operation.

If no _id field is present in a document, one will be added to the original document.

An optional hash reference of options may be provided. The only valid option is ordered, which defaults to true. When true, the server will halt insertions after the first error (if any). When false, all documents will be processed and any error will only be thrown after all insertions are attempted.

On MongoDB servers before version 2.6, insert_many bulk operations are emulated with individual inserts to capture error information. On 2.6 or later, this method will be significantly faster than individual insert_one calls.

delete_one

$res = $coll->delete_one( $filter );
$res = $coll->delete_one( { _id => $id } );

Deletes a single document that matches a filter expression and returns a MongoDB::DeleteResult object.

delete_many

$res = $coll->delete_many( $filter );
$res = $coll->delete_many( { name => "Larry" } );

Deletes all documents that match a filter expression and returns a MongoDB::DeleteResult object.

replace_one

$res = $coll->replace_one( $filter, $replacement );
$res = $coll->replace_one( $filter, $replacement, { upsert => 1 } );

Replaces one document that matches a filter expression and returns a MongoDB::UpdateResult object.

The replacement document must not have any field-update operators in it (e.g. $set).

A hash reference of options may be provided. The only valid option is upsert, which defaults to false. If provided and true, the replacement document will be upserted if no matching document exists.

update_one

$res = $coll->update_one( $filter, $update );
$res = $coll->update_one( $filter, $update, { upsert => 1 } );

Updates one document that matches a filter expression and returns a MongoDB::UpdateResult object.

The update document must have only field-update operators in it (e.g. $set).

A hash reference of options may be provided. The only valid option is upsert, which defaults to false. If provided and true, a new document will be inserted by taking the filter expression and applying the update document operations to it prior to insertion.

update_many

$res = $coll->update_many( $filter, $update );
$res = $coll->update_many( $filter, $update, { upsert => 1 } );

Updates one or more documents that match a filter expression and returns a MongoDB::UpdateResult object.

The update document must have only field-update operators in it (e.g. $set).

A hash reference of options may be provided. The only valid option is upsert, which defaults to false. If provided and true, a new document will be inserted by taking the filter document and applying the update document operations to it prior to insertion.

find

$cursor = $coll->find( $filter );
$cursor = $coll->find( $filter, $options );

$cursor = $coll->find({ i => { '$gt' => 42 } }, {limit => 20});

Executes a query with a filter expression and returns a MongoDB::Cursor object.

The query can be customized using MongoDB::Cursor methods, or with an optional hash reference of options.

Valid options include:

  • allowPartialResults - get partial results from a mongos if some shards are down (instead of throwing an error).

  • batchSize – the number of documents to return per batch.

  • comment – attaches a comment to the query. If $comment also exists in the modifiers document, the comment field overwrites $comment.

  • cursorType – indicates the type of cursor to use. It must be one of three string values: 'non_tailable' (the default), 'tailable', and 'tailable_await'.

  • limit – the maximum number of documents to return.

  • maxTimeMS – the maximum amount of time to allow the query to run. If $maxTimeMS also exists in the modifiers document, the maxTimeMS field overwrites $maxTimeMS.

  • modifiers – a hash reference of query modifiers modifying the output or behavior of a query.

  • noCursorTimeout – if true, prevents the server from timing out a cursor after a period of inactivity

  • projection - a hash reference defining fields to return. See "limit fields to return" in the MongoDB documentation for details.

  • skip – the number of documents to skip before returning.

  • sort – an ordered document defining the order in which to return matching documents. If $orderby also exists in the modifiers document, the sort field overwrites $orderby. See docs for $orderby.

For more infomation, see the Read Operations Overview in the MongoDB documentation.

Note, a MongoDB::Cursor object holds the query and does not issue the query to the server until the request method is called on it or until an iterator method like next is called. Performance will be better directly on a MongoDB::QueryResult object:

my $query_result = $coll->find( $filter )->result;

while ( my $next = $query_result->next ) {
    ...
}

find_one

$doc = $collection->find_one( $filter, $projection );
$doc = $collection->find_one( $filter, $projection, $options );

Executes a query with a filter expression and returns a single document.

If a projection argument is provided, it must be a hash reference specifying fields to return. See Limit fields to return in the MongoDB documentation for details.

If only a filter is provided or if the projection document is an empty hash reference, all fields will be returned.

my $doc = $collection->find_one( $filter );
my $doc = $collection->find_one( $filter, {}, $options );

A hash reference of options may be provided as a third argument. Valid keys include:

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run.

  • sort – an ordered document defining the order in which to return matching documents. If $orderby also exists in the modifiers document, the sort field overwrites $orderby. See docs for $orderby.

See also core documentation on querying: http://docs.mongodb.org/manual/core/read/.

find_one_and_delete

$doc = $coll->find_one_and_delete( $filter );
$doc = $coll->find_one_and_delete( $filter, $options );

Given a filter expression, this deletes a document from the database and returns it as it appeared before it was deleted.

A hash reference of options may be provided. Valid keys include:

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run.

  • projection - a hash reference defining fields to return. See "limit fields to return" in the MongoDB documentation for details.

  • sort – an ordered document defining the order in which to return matching documents. See docs for $orderby.

find_one_and_replace

$doc = $coll->find_one_and_replace( $filter, $replacement );
$doc = $coll->find_one_and_replace( $filter, $replacement, $options );

Given a filter expression and a replacement document, this replaces a document from the database and returns it as it was either right before or right after the replacement. The default is 'before'.

The replacement document must not have any field-update operators in it (e.g. $set).

A hash reference of options may be provided. Valid keys include:

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run.

  • projection - a hash reference defining fields to return. See "limit fields to return" in the MongoDB documentation for details.

  • returnDocument – either the string 'before' or 'after', to indicate whether the returned document should be the one before or after replacement. The default is 'before'.

  • sort – an ordered document defining the order in which to return matching documents. See docs for $orderby.

  • upsert – defaults to false; if true, a new document will be added if one is not found

find_one_and_update

$doc = $coll->find_one_and_update( $filter, $update );
$doc = $coll->find_one_and_update( $filter, $update, $options );

Given a filter expression and a document of update operators, this updates a single document and returns it as it was either right before or right after the update. The default is 'before'.

The update document must contain only field-update operators (e.g. $set).

A hash reference of options may be provided. Valid keys include:

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run.

  • projection - a hash reference defining fields to return. See "limit fields to return" in the MongoDB documentation for details.

  • returnDocument – either the string 'before' or 'after', to indicate whether the returned document should be the one before or after replacement. The default is 'before'.

  • sort – an ordered document defining the order in which to return matching documents. See docs for $orderby.

  • upsert – defaults to false; if true, a new document will be added if one is not found

aggregate

@pipeline = (
    { '$group' => { _id => '$state,' totalPop => { '$sum' => '$pop' } } },
    { '$match' => { totalPop => { '$gte' => 10 * 1000 * 1000 } } }
);

$result = $collection->aggregate( \@pipeline );
$result = $collection->aggregate( \@pipeline, $options );

Runs a query using the MongoDB 2.2+ aggregation framework and returns a MongoDB::QueryResult object.

The first argument must be an array-ref of aggregation pipeline documents. Each pipeline document must be a hash reference.

A hash reference of options may be provided. Valid keys include:

  • allowDiskUse – if, true enables writing to temporary files.

  • batchSize – the number of documents to return per batch.

  • explain – if true, return a single document with execution information.

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run.

Note MongoDB 2.6+ added the '$out' pipeline operator. If this operator is used to write aggregation results directly to a collection, an empty result will be returned. Create a new collection> object to query the generated result collection. When $out is used, the command is treated as a write operation and read preference is ignored.

See Aggregation in the MongoDB manual for more information on how to construct aggregation queries.

count

$count = $coll->count( $filter );
$count = $coll->count( $filter, $options );

Returns a count of documents matching a filter expression.

A hash reference of options may be provided. Valid keys include:

  • hintspecify an index to use; must be a string, array reference, hash reference or Tie::IxHash object.

  • limit – the maximum number of documents to count.

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run.

  • skip – the number of documents to skip before counting documents.

NOTE: On a sharded cluster, count can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress. See count command documentation for details and a work-around using "aggregate".

distinct

$result = $coll->count( $fieldname );
$result = $coll->count( $fieldname, $filter );
$result = $coll->count( $fieldname, $filter, $options );

Returns a MongoDB::QueryResult object that will provide distinct values for a specified field name.

The query may be limited by an optional filter expression.

A hash reference of options may be provided. Valid keys include:

  • maxTimeMS – the maximum amount of time in milliseconds to allow the command to run.

See documentation for the distinct command for details.

parallel_scan

@result_objs = $collection->parallel_scan(10);

Returns one or more MongoDB::QueryResult objects to scan the collection in parallel. The argument is the maximum number of MongoDB::QueryResult objects to return and must be a positive integer between 1 and 10,000.

As long as the collection is not modified during scanning, each document will appear only once in one of the cursors' result sets.

Note: the server may return fewer cursors than requested, depending on the underlying storage engine and resource availability.

rename

$newcollection = $collection->rename("mynewcollection");

Renames the collection. If a collection already exists with the new collection name, this method will throw an exception.

It returns a new MongoDB::Collection object corresponding to the renamed collection.

ensure_index

$collection->ensure_index( $keys );
$collection->ensure_index( $keys, $options );
$collection->ensure_index(["foo" => 1, "bar" => -1], { unique => 1 });

Makes sure the given $keys of this collection are indexed. $keys can be an array reference, hash reference, or Tie::IxHash. Array references or Tie::IxHash is preferred for multi-key indexes, so that the keys are in the correct order. 1 creates an ascending index, -1 creates a descending index.

If an optional $options argument is provided, those options are passed through to the database to modify index creation. Typical options include:

  • background – build the index in the background

  • name – a name for the index; one will be generated if not provided

  • unique – if true, inserting duplicates will fail

See the MongoDB index documentation for more information on indexing and index options.

Returns true on success and throws an exception on failure.

Note: index creation can take longer than the network timeout, resulting in an exception. If this is a concern, consider setting the background option.

save($doc, $options)

$collection->save({"author" => "joe"});
$post = $collection->find_one;

$post->{author} = {"name" => "joe", "id" => 123, "phone" => "555-5555"};

$collection->save( $post );
$collection->save( $post, { safe => 1 } )

Inserts a document into the database if it does not have an _id field, upserts it if it does have an _id field.

The return types for this function are a bit of a mess, as it will return the _id if a new document was inserted, 1 if an upsert occurred, and croak if the safe option was set and an error occurred. You can also check if the save succeeded by doing an unsafe save, then calling "last_error($options?)" in MongoDB::Database.

validate

$collection->validate;

Asks the server to validate this collection. Returns a hash of the form:

{
    'ok' => '1',
    'ns' => 'foo.bar',
    'result' => info
}

where info is a string of information about the collection.

drop_indexes

$collection->drop_indexes;

Removes all indexes from this collection.

drop_index ($index_name)

$collection->drop_index('foo_1');

Removes an index called $index_name from this collection. Use MongoDB::Collection::get_indexes to find the index name.

get_indexes

@indexes = $collection->get_indexes;

Returns a list of all indexes of this collection. Each index contains ns, name, and key fields of the form:

{
    'ns' => 'db_name.collection_name',
    'name' => 'index_name',
    'key' => {
        'key1' => dir1,
        'key2' => dir2,
        ...
        'keyN' => dirN
    }
}

where dirX is 1 or -1, depending on if the index is ascending or descending on that key.

drop

$collection->drop;

Deletes a collection as well as all of its indexes.

ordered_bulk

$bulk = $coll->ordered_bulk;
$bulk->insert( $doc1 );
$bulk->insert( $doc2 );
...
$result = $bulk->execute;

Returns a MongoDB::BulkWrite object to group write operations into fewer network round-trips. This method creates an ordered operation, where operations halt after the first error. See MongoDB::BulkWrite for more details.

The method initialize_ordered_bulk_op may be used as an alias.

unordered_bulk

This method works just like "ordered_bulk" except that the order that operations are sent to the database is not guaranteed and errors do not halt processing. See MongoDB::BulkWrite for more details.

The method initialize_unordered_bulk_op may be used as an alias.

bulk_write

$res = $coll->bulk_write( [ @requests ], $options )

This method provides syntactic sugar to construct and execute a bulk operation directly, without using initialize_ordered_bulk or initialize_unordered_bulk to generate a MongoDB::BulkWrite object and then calling methods on it. It returns a MongoDB::BulkWriteResponse object just like the MongoDB::BulkWrite execute method.

The first argument must be an array reference of requests. Requests consist of pairs of a MongoDB::Collection write method name (e.g. insert_one, delete_many) and an array reference of arguments to the corresponding method name. They may be given as pairs, or as hash or array references:

# pairs -- most efficient
@requests = (
    insert_one  => [ { x => 1 } ],
    replace_one => [ { x => 1 }, { x => 4 } ],
    delete_one  => [ { x => 4 } ],
    update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ],
);

# hash references
@requests = (
    { insert_one  => [ { x => 1 } ] },
    { replace_one => [ { x => 1 }, { x => 4 } ] },
    { delete_one  => [ { x => 4 } ] },
    { update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ] },
);

# array references
@requests = (
    [ insert_one  => [ { x => 1 } ] ],
    [ replace_one => [ { x => 1 }, { x => 4 } ] ],
    [ delete_one  => [ { x => 4 } ] ],
    [ update_many => [ { x => { '$gt' => 5 } }, { '$inc' => { x => 1 } } ] ],
);

Valid method names include insert_one, insert_many, delete_one, delete_many replace_one, update_one, update_many.

An optional hash reference of options may be provided. The only valid value is ordered. It defaults to true. When true, the bulk operation is executed like "initialize_ordered_bulk". When false, the bulk operation is executed like "initialize_unordered_bulk".

See MongoDB::BulkWrite for more details on bulk writes. Be advised that the legacy Bulk API method names differ slightly from MongoDB::Collection method names.

DEPRECATIONS

With the introduction of the common driver CRUD API, these legacy methods have been deprecated:

  • batch_insert

  • find_and_modify

  • insert

  • query

  • remove

  • update

The get_collection method is deprecated; it implied a 'subcollection' relationship that is purely notional.

The methods still exist, but are no longer documented. In a future version they will warn when used, then will eventually be removed.

AUTHORS

  • David Golden <david@mongodb.com>

  • Mike Friedman <friedo@mongodb.com>

  • Kristina Chodorow <kristina@mongodb.com>

  • Florian Ragwitz <rafl@debian.org>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2015 by MongoDB, Inc..

This is free software, licensed under:

The Apache License, Version 2.0, January 2004