|
NAMEMongoDB::Collection - A MongoDB CollectionVERSIONversion v2.2.2SYNOPSIS# 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 ) { ... } DESCRIPTIONThis 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. USAGEError handlingUnless 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_one( $doc ) } catch { if ( $_->$_isa("MongoDB::DuplicateKeyError" ) { ... } else { ... } }; To retry failures automatically, consider using Try::Tiny::Retry. TransactionsTo conduct operations in a transactions, get a MongoDB::ClientSession from "start_session" in MongoDB::MongoClient. Start the transaction on the session using "start_transaction" and pass the session as an option to all operations. Then call "commit_transaction" or "abort_transaction" on the session. See the MongoDB::ClientSession for options and usage details.For detailed instructions on using transactions with MongoDB, see the MongoDB manual page: Transactions <https://docs.mongodb.com/master/core/transactions>. TerminologyDocumentA 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". ATTRIBUTESdatabaseThe MongoDB::Database representing the database that contains the collection.nameThe name of the collection.read_preferenceA 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_concernA 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_concernA 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_msSpecifies 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_codecAn object that provides the "encode_one" and "decode_one" methods, such as from BSON. It may be initialized with a hash reference that will be coerced into a new BSON object. By default it will be inherited from a MongoDB::Database object.METHODSclient$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:
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:
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 } ); $res = $coll->delete_one( $filter, { collation => { locale => "en_US" } } ); Deletes a single document that matches a filter expression and returns a MongoDB::DeleteResult or MongoDB::UnacknowledgedResult object. A hash reference of options may be provided. Valid options include:
delete_many$res = $coll->delete_many( $filter ); $res = $coll->delete_many( { name => "Larry" } ); $res = $coll->delete_many( $filter, { collation => { locale => "en_US" } } ); Deletes all documents that match a filter expression and returns a MongoDB::DeleteResult or MongoDB::UnacknowledgedResult object. Valid options include:
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:
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:
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:
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 lazy "MongoDB::Cursor" object. (The query is not immediately issued to the server; see below for details.) The query can be customized using MongoDB::Cursor methods, or with an optional hash reference of options. Valid options include:
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:
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:
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:
watchWatches for changes on this collection-Perform an aggregation with an implicit initial $changeStream stage and returns a MongoDB::ChangeStream result which can be used to iterate over the changes in the collection. This functionality is available since MongoDB 3.6. my $stream = $collection->watch(); my $stream = $collection->watch( \@pipeline ); my $stream = $collection->watch( \@pipeline, \%options ); while (1) { # This inner loop will only run until no more changes are # available. while (my $change = $stream->next) { # process $change } } The returned stream will not block forever waiting for changes. If you want to respond to changes over a longer time use "maxAwaitTimeMS" and regularly call "next" in a loop. Note: Using this helper method is preferred to manually aggregating with a $changeStream stage, since it will automatically resume when the connection was terminated. The optional 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. Not all pipeline stages are supported after $changeStream. The optional second argument is a hash reference with options:
See "aggregate" for more available options. See the manual section on Change Streams <https://docs.mongodb.com/manual/changeStreams/> for general usage information on change streams. See the Change Streams specification <https://github.com/mongodb/specifications/blob/master/source/change-streams.rst> for details on change streams. 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. Note: Some pipeline documents have ordered arguments, such as $sort. Be sure to provide these argument using Tie::IxHash. E.g.: { '$sort' => Tie::IxHash->new( age => -1, posts => 1 ) } A hash reference of options may be provided. Valid keys include:
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_documents$count = $coll->count_documents( $filter ); $count = $coll->count_documents( $filter, $options ); Returns a count of documents matching a filter expression. To return a count of all documents, use an empty hash reference as the filter. NOTE: this may result in a scan of all documents in the collection. For a fast count of the total documents in a collection see "estimated_document_count" instead. A hash reference of options may be provided. Valid keys include:
NOTE: When upgrading from the deprecated "count" method, some legacy operators are not supported and must be replaced: +-------------+--------------------------------+ | Legacy | Modern Replacement | +=============+================================+ | $where | $expr (Requires MongoDB 3.6+) | +-------------+--------------------------------+ | $near | $geoWithin with $center | +-------------+--------------------------------+ | $nearSphere | $geoWithin with $centerSphere | +-------------+--------------------------------+ estimated_document_count$count = $coll->estimated_document_count(); $count = $coll->estimated_document_count($options); Returns an estimated count of documents based on collection metadata. NOTE: this method does not support sessions or transactions. A hash reference of options may be provided. Valid keys include:
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:
See documentation for the distinct command <http://docs.mongodb.org/manual/reference/command/distinct/> for details. rename$newcollection = $collection->rename("mynewcollection"); Renames the collection. If a collection already exists with the new collection name, this method will throw an exception. A hashref of options may be provided. Valid options include:
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_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. A hash reference of options may be provided. Valid options include:
unordered_bulkThis 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:
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:
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. AUTHORS
COPYRIGHT AND LICENSEThis software is Copyright (c) 2020 by MongoDB, Inc.This is free software, licensed under: The Apache License, Version 2.0, January 2004
Visit the GSP FreeBSD Man Page Interface. |