MongoDB::Collection(3) A MongoDB Collection

VERSION

version v1.2.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 explicitly 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 <http://docs.mongodb.org/manual/tutorial/query-documents/> 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.

read_concern

A MongoDB::ReadConcern object. May be initialized with a hash reference or a string that will be coerced into the level of read concern.

By default it will be inherited from a MongoDB::Database object.

max_time_ms

Specifies the default maximum amount of time in milliseconds that the server should use for working on a query.

Note: this will only be used for server versions 2.6 or greater, as that was when the $maxTimeMS meta-operator was introduced.

bson_codec

An object that provides the "encode_one" and "decode_one" methods, such as from MongoDB::BSON. It may be initialized with a hash reference that will be coerced into a new MongoDB::BSON 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''.

indexes

    $indexes = $collection->indexes;
    $collection->indexes->create_one( [ x => 1 ], { unique => 1 } );
    $collection->indexes->drop_all;

Returns a MongoDB::IndexView object for managing the indexes associated with the collection.

clone

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

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

with_codec

    $coll2 = $coll1->with_codec( $new_codec );
    $coll2 = $coll1->with_codec( prefer_numeric => 1 );

Constructs a copy of the original collection, but clones the "bson_codec". If given an object that does "encode_one" and "decode_one", it is equivalent to:

    $coll2 = $coll1->clone( bson_codec => $new_codec );

If given a hash reference or a list of key/value pairs, it is equivalent to:

    $coll2 = $coll1->clone(
        bson_codec => $coll1->bson_codec->clone( @list )
    );

insert_one

    $res = $coll->insert_one( $document );
    $res = $coll->insert_one( $document, $options );
    $id = $res->inserted_id;

Inserts a single document into the database and returns a MongoDB::InsertOneResult or MongoDB::UnacknowledgedResult object.

If no "_id" field is present, one will be added when a document is serialized for the database without modifying the original document. The generated "_id" may be retrieved from the result object.

An optional hash reference of options may be given.

Valid options include:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

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 or MongoDB::UnacknowledgedResult. This is syntactic sugar for doing a MongoDB::BulkWrite operation.

If no "_id" field is present, one will be added when a document is serialized for the database without modifying the original document. The generated "_id" may be retrieved from the result object.

An optional hash reference of options may be provided.

Valid options include:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
  • "ordered" – 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. The default is true.

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 or MongoDB::UnacknowledgedResult 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 or MongoDB::UnacknowledgedResult 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 or MongoDB::UnacknowledgedResult object.

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

A hash reference of options may be provided.

Valid options include:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
  • "upsert" – defaults to false; if true, a new document will be added if one is not found

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 or MongoDB::UnacknowledgedResult object.

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

A hash reference of options may be provided.

Valid options include:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
  • "upsert" – defaults to false; if true, a new document will be added if one is not found 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 or MongoDB::UnacknowledgedResult object.

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

A hash reference of options may be provided.

Valid options include:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
  • "upsert" – defaults to false; if true, a new document will be added if one is not found by taking the filter expression 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.
  • "maxAwaitTimeMS" – the maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. This only applies to a "cursorType" of 'tailable_await'; the option is otherwise ignored. (Note, this will be ignored for servers before version 3.2.)
  • "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. (Note, this will be ignored for servers before version 2.6.)
  • "modifiers" – a hash reference of query modifiers <http://docs.mongodb.org/manual/reference/operator/query-modifier/> 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 <http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/>" 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 <http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.

For more information, see the Read Operations Overview <http://docs.mongodb.org/manual/core/read-operations-introduction/> in the MongoDB documentation.

Note, a MongoDB::Cursor object holds the query and does not issue the query to the server until the result 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 <http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/> 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. (Note, this will be ignored for servers before version 2.6.)
  • "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 <http://docs.mongodb.org/manual/reference/operator/meta/orderby/>.

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

find_id

    $doc = $collection->find_id( $id );
    $doc = $collection->find_id( $id, $projection );
    $doc = $collection->find_id( $id, $projection, $options );

Executes a query with a filter expression of "{ _id => $id }" and returns a single document.

See the find_one documentation for details on the $projection and $options parameters.

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:

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:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
  • "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 <http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/>" 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 <http://docs.mongodb.org/manual/reference/operator/meta/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:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
  • "maxTimeMS" – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 2.6.)
  • "projection" - a hash reference defining fields to return. See "limit fields to return <http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/>" 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 <http://docs.mongodb.org/manual/reference/operator/meta/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 <http://docs.mongodb.org/manual/core/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.
  • "bypassDocumentValidation" - skips document validation, if enabled. (Note, this will be ignored for servers before version 3.2.)
  • "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, this will be ignored for servers before version 2.6.)

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 <http://docs.mongodb.org/manual/aggregation/> in the MongoDB manual for more information on how to construct aggregation queries.

Note The use of aggregation cursors is automatic based on your server version. However, if migrating a sharded cluster from MongoDB 2.4 to 2.6 or later, you must upgrade your mongod servers first before your mongos routers or aggregation queries will fail. As a workaround, you may pass "cursor => undef" as an option.

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:

  • "hint" – specify an index to use <http://docs.mongodb.org/manual/reference/command/count/#specify-the-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. (Note, this will be ignored for servers before version 2.6.)
  • "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 <http://docs.mongodb.org/manual/reference/command/count/#behavior> for details and a work-around using ``aggregate''.

distinct

    $result = $coll->distinct( $fieldname );
    $result = $coll->distinct( $fieldname, $filter );
    $result = $coll->distinct( $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. (Note, this will be ignored for servers before version 2.6.)

See documentation for the distinct command <http://docs.mongodb.org/manual/reference/command/distinct/> 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.

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.

A hash reference of options may be provided.

Valid options include:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

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.

A hash reference of options may be provided.

Valid options include:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.

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.

Valid options include:

  • "bypassDocumentValidation" - skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.
  • "ordered" – when true, the bulk operation is executed like ``initialize_ordered_bulk''. When false, the bulk operation is executed like ``initialize_unordered_bulk''. The default is true.

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
  • save

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

The "ensure_index", "drop_indexes", "drop_index", and "get_index" methods are deprecated. The new MongoDB::IndexView class is accessible through the "indexes" method, and offer greater consistency in behavior across drivers.

The "validate" method is deprecated as the return value was inconsistent over time. Users who need it should execute it via "run_command" instead.

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

AUTHORS

COPYRIGHT AND LICENSE

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

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004