MongoDB::Collection - A MongoDB Collection
version v1.4.0
# 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 ) { ... }
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.
new
get_collection
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_one( $doc ) } catch { if ( $_->$_isa("MongoDB::DuplicateKeyError" ) { ... } else { ... } };
To retry failures automatically, consider using Try::Tiny::Retry.
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.
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.
A filter expression provides the query criteria to select a document for deletion. It must be an "Ordered document".
The MongoDB::Database representing the database that contains the collection.
The name of the collection.
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.
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.
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.
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.
$maxTimeMS
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.
encode_one
decode_one
$client = $coll->client;
Returns the MongoDB::MongoClient object associated with this object.
$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".
full_name
$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.
$coll2 = $coll1->clone( write_concern => { w => 2 } );
Constructs a copy of the original collection, but allows changing attributes in the copy.
$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:
bson_codec
$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 ) );
$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.
_id
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.
bypassDocumentValidation
$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.
An optional hash reference of options may be provided.
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.
ordered
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.
insert_many
insert_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.
$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.
$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).
$set
A hash reference of options may be provided.
upsert – defaults to false; if true, a new document will be added if one is not found
upsert
$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).
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.
$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.
$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.
MongoDB::Cursor
The query can be customized using MongoDB::Cursor methods, or with an optional hash reference of options.
allowPartialResults - get partial results from a mongos if some shards are down (instead of throwing an error).
allowPartialResults
batchSize – the number of documents to return per batch.
batchSize
comment – attaches a comment to the query. If $comment also exists in the modifiers document, the comment field overwrites $comment.
comment
$comment
modifiers
cursorType – indicates the type of cursor to use. It must be one of three string values: 'non_tailable' (the default), 'tailable', and 'tailable_await'.
cursorType
'non_tailable'
'tailable'
'tailable_await'
limit – the maximum number of documents to return.
limit
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.)
maxAwaitTimeMS
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.)
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
noCursorTimeout
projection - a hash reference defining fields to return. See "limit fields to return" in the MongoDB documentation for details.
projection
skip – the number of documents to skip before returning.
skip
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.
sort
$orderby
For more information, 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 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 ) { ... }
$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. (Note, this will be ignored for servers before version 2.6.)
See also core documentation on querying: http://docs.mongodb.org/manual/core/read/.
$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.
{ _id => $id }
See the find_one documentation for details on the $projection and $options parameters.
$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:
sort – an ordered document defining the order in which to return matching documents. See docs for $orderby.
$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'.
maxTimeMS – the maximum amount of time in milliseconds to allow the command to run.
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'.
returnDocument
'before'
'after'
$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).
@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.
allowDiskUse – if, true enables writing to temporary files.
allowDiskUse
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.
explain
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.
$out
See 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.
cursor => undef
$count = $coll->count( $filter ); $count = $coll->count( $filter, $options );
Returns a count of documents matching a filter expression.
hint – specify an index to use; must be a string, array reference, hash reference or Tie::IxHash object.
hint
limit – the maximum number of documents to count.
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".
count
$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.
See documentation for the distinct command for details.
@result_objs = $collection->parallel_scan(10); @result_objs = $collection->parallel_scan(10, $options );
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.
maxTimeMS – the maximum amount of time in milliseconds to allow the command to run. (Note, this will be ignored for servers before version 3.4.)
$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.
$collection->drop;
Deletes a collection as well as all of its indexes.
$bulk = $coll->ordered_bulk; $bulk->insert_one( $doc1 ); $bulk->insert_one( $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.
initialize_ordered_bulk_op
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.
initialize_unordered_bulk_op
$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.
initialize_ordered_bulk
initialize_unordered_bulk
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:
delete_many
# 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.
delete_one
replace_one
update_one
update_many
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.
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 accessable through the indexes method, and offer greater consistency in behavior across drivers.
ensure_index
drop_indexes
drop_index
get_index
indexes
The validate method is deprecated as the return value was inconsistent over time. Users who need it should execute it via run_command instead.
validate
run_command
The methods still exist, but are no longer documented. In a future version they will warn when used, then will eventually be removed.
David Golden <david@mongodb.com>
Mike Friedman <friedo@friedo.com>
Kristina Chodorow <k.chodorow@gmail.com>
Florian Ragwitz <rafl@debian.org>
This software is Copyright (c) 2016 by MongoDB, Inc.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
To install MongoDB, copy and paste the appropriate command in to your terminal.
cpanm
cpanm MongoDB
CPAN shell
perl -MCPAN -e shell install MongoDB
For more information on module installation, please visit the detailed CPAN module installation guide.