The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

MongoDB::Collection - A MongoDB Collection

VERSION

version v0.999.998.2

SYNOPSIS

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

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

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

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

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.

ATTRIBUTES

name

The name of the collection.

full_name

The full_name of the collection, including the namespace of the database it's in.

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.

write_concern

A MongoDB::WriteConcern object. It may be initialized with a hash reference that will be coerced into a new MongoDB::WriteConcern object.

METHODS

clone

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

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

get_collection ($name)

    my $collection = $database->get_collection('foo');

Returns a MongoDB::Collection for the collection called $name within this collection.

get_collection

Collection names can be chained together to access subcollections. For instance, the collection foo.bar can be accessed with either:

    my $collection = $db->get_collection( 'foo' )->get_collection( 'bar' );

or

    my $collection = $db->get_collection( 'foo.bar' );

find, query

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

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

Executes a query with the given $filter and returns a MongoDB::Cursor with the results. $filter can be a hash reference, Tie::IxHash, or array reference (with an even number of elements).

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 enumerated 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 meta-operators 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 – a Tie::IxHash or array reference of key value pairs defining the order in which to return matching documents. If $orderby also exists * in the modifiers document, the sort field overwrites $orderby.

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

The query method is a legacy alias for find.

find_one($query, $fields?, $options?)

    my $object = $collection->find_one({ name => 'Resi' });
    my $object = $collection->find_one({ name => 'Resi' }, { name => 1, age => 1});
    my $object = $collection->find_one({ name => 'Resi' }, {}, {max_time_ms => 100});

Executes the given $query and returns the first object matching it. $query can be a hash reference, Tie::IxHash, or array reference (with an even number of elements). If $fields is specified, the resulting document will only include the fields given (and the _id field) which can cut down on wire traffic. If $options is specified, the cursor will be set with the contained options.

insert ($object, $options?)

    my $id1 = $coll->insert({ name => 'mongo', type => 'database' });
    my $id2 = $coll->insert({ name => 'mongo', type => 'database' }, {safe => 1});

Inserts the given $object into the database and returns it's id value. $object can be a hash reference, a reference to an array with an even number of elements, or a Tie::IxHash. The id is the _id value specified in the data or a MongoDB::OID.

The optional $options parameter can be used to specify if this is a safe insert. A safe insert will check with the database if the insert succeeded and croak if it did not. You can also check if the insert succeeded by doing an unsafe insert, then calling "last_error($options?)" in MongoDB::Database.

See also core documentation on insert: http://docs.mongodb.org/manual/core/create/.

batch_insert (\@array, $options)

    my @ids = $collection->batch_insert([{name => "Joe"}, {name => "Fred"}, {name => "Sam"}]);

Inserts each of the documents in the array into the database and returns an array of their _id fields.

The optional $options parameter can be used to specify if this is a safe insert. A safe insert will check with the database if the insert succeeded and croak if it did not. You can also check if the inserts succeeded by doing an unsafe batch insert, then calling "last_error($options?)" in MongoDB::Database.

update (\%criteria, \%object, \%options?)

    $collection->update({'x' => 3}, {'$inc' => {'count' => -1} }, {"upsert" => 1, "multiple" => 1});

Updates an existing $object matching $criteria in the database.

Returns 1 unless the safe option is set. If safe is set, this will return a hash of information about the update, including number of documents updated (n). If safe is set and the update fails, update will croak. You can also check if the update succeeded by doing an unsafe update, then calling "last_error($options?)" in MongoDB::Database.

update can take a hash reference of options. The options currently supported are:

upsert If no object matching $criteria is found, $object will be inserted.
multiple|multi All of the documents that match $criteria will be updated, not just the first document found. (Only available with database version 1.1.3 and newer.) An error will be throw if both multiple and multi exist and their boolean values differ.
safe If the update fails and safe is set, the update will croak.

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

find_and_modify

    my $result = $collection->find_and_modify( { query => { ... }, update => { ... } } );

Perform an atomic update. find_and_modify guarantees that nothing else will come along and change the queried documents before the update is performed.

Returns the old version of the document, unless new = 1> is specified. If no documents match the query, it returns nothing.

aggregate

    my $result = $collection->aggregate( [ ... ] );

Run a query using the MongoDB 2.2+ aggregation framework. The first argument is an array-ref of aggregation pipeline operators.

The type of return value from aggregate depends on how you use it.

  • By default, the aggregation framework returns a document with an embedded array of results, and the aggregate method returns a reference to that array.

  • MongoDB 2.6+ supports returning cursors from aggregation queries, allowing you to bypass the 16MB size limit of documents. If you specifiy a cursor option, the aggregate method will return a MongoDB::QueryResult object which can be iterated in the normal fashion.

        my $cursor = $collection->aggregate( [ ... ], { cursor => 1 } );

    Specifying a cursor option will cause an error on versions of MongoDB below 2.6.

    The cursor option may also have some useful options of its own. Currently, the only one is batchSize, which allows you to control how frequently the cursor must go back to the database for more documents.

        my $cursor = $collection->aggregate( [ ... ], { cursor => { batchSize => 10 } } );
  • MongoDB 2.6+ supports an explain option to aggregation queries to retrieve data about how the server will process a query pipeline.

        my $result = $collection->aggregate( [ ... ], { explain => 1 } );

    In this case, aggregate will return a document (not an array) containing the explanation structure.

  • Finally, MongoDB 2.6+ will return an empty results array if the $out pipeline operator is used to write aggregation results directly to a collection. Create a new Collection object to query the result collection.

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

parallel_scan($max_cursors)

    my @query_results = $collection->parallel_scan(10);

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.

Only iteration methods may be called on parallel scan cursors.

If an error occurs, an exception will be thrown.

rename ("newcollectionname")

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

Renames the collection. It expects that the new name is currently not in use.

Returns the new collection. If a collection already exists with that new collection name this will die.

remove ($query?, $options?)

    $collection->remove({ answer => { '$ne' => 42 } });

Removes all objects matching the given $query from the database. If no parameters are given, removes all objects from the collection (but does not delete indexes, as MongoDB::Collection::drop does).

Returns 1 unless the safe option is set. If safe is set and the remove succeeds, remove will return a hash of information about the remove, including how many documents were removed (n). If the remove fails and safe is set, remove will croak. You can also check if the remove succeeded by doing an unsafe remove, then calling "last_error($options?)" in MongoDB::Database.

remove can take a hash reference of options. The options currently supported are

just_one Only one matching document to be removed.
safe If the update fails and safe is set, this function will croak.

See also core documentation on remove: http://docs.mongodb.org/manual/core/delete/.

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"});
    my $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.

count($query?)

    my $n_objects = $collection->count({ name => 'Bob' });

Counts the number of objects in this collection that match the given $query. If no query is given, the total number of objects in the collection is returned.

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

    my @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.

initialize_ordered_bulk_op, ordered_bulk

    my $bulk = $collection->initialize_ordered_bulk_op;
    $bulk->insert( $doc1 );
    $bulk->insert( $doc2 );
    ...
    my $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 ordered_bulk may be used as an alias for initialize_ordered_bulk_op.

initialize_unordered_bulk_op, unordered_bulk

This method works just like "initialize_ordered_bulk_op" 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 unordered_bulk may be used as an alias for initialize_unordered_bulk_op.

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