MongoD...lection(3pm)
okay bestie, so this is MongoD...lection(3pm) out of the User Contributed Perl Documentation situation π it's part 1 of 4, so buckle up, we're not done yet.
β¨ NAME β¨
MongoDB::Collection β it's A MongoDB Collection, your whole entire vibe π
π« VERSION π«
version v2.2.2 β
π¦ SYNOPSIS π¦
okay so like, here's the whole serve in one glance:
# 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 πΈ
So this class is literally the model of a MongoDB collection, and it hands you an API for interacting with it. That's the whole thing. π«Ά
And real talk: you basically never build one of these yourself with new. Nope. Instead you call get_collection on a MongoDB::Database object and let it do the work. iconic behavior honestly β¨
π«Ά USAGE π«Ά
π Error handling π
Unless it's explicitly documented otherwise, every single method throws exceptions if an error happens. The error types live over in MongoDB::Error, go read up.
To catch and handle those errors, the recommended besties are Try::Tiny and Safe::Isa:
use Try::Tiny;
use Safe::Isa; # provides $_isa
try {
$coll->insert_one( $doc )
}
catch {
if ( $_->$_isa("MongoDB::DuplicateKeyError" ) {
...
}
else {
...
}
};
And if you want failures to auto-retry, consider Try::Tiny::Retry. no cap π
π¦ Transactions π¦
Wanna run operations inside a transaction? Get a MongoDB::ClientSession from start_session in MongoDB::MongoClient. Then start the transaction on the session using start_transaction, and pass that session as an option to all the operations. Then you call commit_transaction or abort_transaction on the session. Options and usage deets be in MongoDB::ClientSession. β¨
For the full detailed instructions on using transactions with MongoDB, hit up the MongoDB manual page: Transactions at https://docs.mongodb.com/master/core/transactions.
π Terminology π
π Document
A collection of key-value pairs. A Perl hash is a document. You can also use array references with an even number of elements, or Tie::IxHash objects, as documents. slay.
π’ Ordered document
Lots of MongoDB::Collection method params or options require an ordered document: an ordered list of key/value pairs. And here's the tea: Perl's hashes are not ordered, and since Perl v5.18 they're guaranteed to have random order. So whenever an ordered document is called for, you may use an array reference of pairs or a Tie::IxHash object. And if there's only one key/value pair, a hash reference is fine. π
π Filter expression
A filter expression gives the query criteria at http://docs.mongodb.org/manual/tutorial/query-documents/ to select a document for deletion. It must be an "Ordered document". periodt.
π ATTRIBUTES π
ποΈ database
The MongoDB::Database representing the database that contains the collection. π
π·οΈ name
The name of the collection. simple as that.
π read_preference
A MongoDB::ReadPreference object. You may initialize it with a string matching one of the valid read preference modes, or a hash reference that will get coerced into a new MongoDB::ReadPreference object. By default it gets inherited from a MongoDB::Database object. πΈ
βοΈ write_concern
A MongoDB::WriteConcern object. You may initialize it with a hash reference that will be coerced into a new MongoDB::WriteConcern object. By default it gets 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 gets inherited from a MongoDB::Database object. π¦
β±οΈ max_time_ms
Specifies the default max amount of time, in milliseconds, that the server should use for working on a query.
Note: this is only used for server versions 2.6 or greater, since that's when the $maxTimeMS meta-operator got introduced. okurrr π
𧬠bson_codec
An object that provides the encode_one and decode_one methods β like one from BSON. You may initialize it with a hash reference that will be coerced into a new BSON object. By default it gets inherited from a MongoDB::Database object. β¨
π METHODS π
π§ client
$client = $coll->client;
Returns the MongoDB::MongoClient object associated with this object. your main character connection π«Ά
π 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. So like, collection "foo" in database "test" would give you a full_name of "test.foo". cute right?
ποΈ 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. go manage ur indexes bestie π
πͺ clone
$coll2 = $coll1->clone( write_concern => { w => 2 } );
Constructs a copy of the original collection, but lets you change attributes in the copy. it's giving twin energy π
π 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 you give it an object that does encode_one and decode_one, it's equivalent to:
$coll2 = $coll1->clone( bson_codec => $new_codec );
And if you give it a hash reference or a list of key/value pairs, it's 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 there's no _id field present, one will be added when the document is serialized for the database β without modifying the original document. The generated _id can be retrieved from the result object. cute, no side effects π¦
An optional hash reference of options may be given.
Valid options include:
bypassDocumentValidationβ skips document validation, if it's enabled; this is ignored for MongoDB servers older than version 3.2. πsessionβ the session to use for these operations. If not supplied, it'll use an implicit session. More info inMongoDB::ClientSession.
ββ 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 there's no _id field present, one will be added when a document is serialized for the database β again, without modifying the original document. The generated _id can be retrieved from the result object. π
An optional hash reference of options may be provided.
Valid options include:
bypassDocumentValidationβ skips document validation, if it's enabled; this is ignored for MongoDB servers older than version 3.2. πsessionβ the session to use for these operations. If not supplied, it'll use an implicit session. More info inMongoDB::ClientSession.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_manybulk operations are emulated with individual inserts, just so error info can be captured. On 2.6 or later, this method will be significantly faster than individualinsert_onecalls. glow up π
ποΈ 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. bye felicia π
A hash reference of options may be provided.
Valid options include:
collationβ a document defining the collation for this operation. See the docs for the format of the collation document here:https://docs.mongodb.com/master/reference/collation/. πsessionβ the session to use for these operations. If not supplied, it'll use an implicit session. More info inMongoDB::ClientSession.
ποΈποΈ 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. okay mass deletion, we love a clean slate β¨
Valid options include:
collationβ a document defining the collation for this operation. See the docs for the format of the collation document here:https://docs.mongodb.com/master/reference/collation/. πsessionβ the session to use for these operations. If not supplied, it'll use an implicit session. More info inMongoDB::ClientSession.
π 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. π
fr fr: the replacement document must not have any field-update operators in it (like $set). like do not do that.
A hash reference of options may be provided.
Valid options include:
bypassDocumentValidationβ skips document validation, if it's enabled; this is ignored for MongoDB servers older than version 3.2. πcollationβ a document defining the collation for this operation. See the docs for the format of the collation document here:https://docs.mongodb.com/master/reference/collation/. πsessionβ the session to use for these operations. If not supplied, it'll use an implicit session. More info inMongoDB::ClientSession.upsertβ defaults to false; if true, a new document will be added if one isn't found. β¨
βοΈ update_one
$res = $coll->update_one( $filter, $update );
$res = $coll->update_one( $filter, $update, { upsert => 1 } );
arrayFiltersβ an array of filter documents telling the server exactly which array elements to modify when your update op is touching an array field. π Only available for MongoDB servers of version 3.6+.bypassDocumentValidationβ skips document validation, if it's enabled on the collection. This gets ignored for MongoDB servers older than version 3.2.collationβ a document defining the collation for this operation. The format of the collation document lives here, bestie: https://docs.mongodb.com/master/reference/collation/ πsessionβ the session to use for these operations. If you don't supply one, it'll use an implicit session. More deets over in MongoDB::ClientSession β¨upsertβ defaults tofalse; iftrue, 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. basically "if it's not there, make it there" π
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 hands you back a MongoDB::UpdateResult or MongoDB::UnacknowledgedResult object. slay π¦
Okay so the update document must have only field-update operators in it (e.g. $set). like that's the whole rule, don't fight it π
A hash reference of options may be provided.
Valid options include:
arrayFiltersβ an array of filter documents that determines which array elements to modify for an update operation on an array field. Only available for MongoDB servers of version 3.6+.bypassDocumentValidationβ skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2.collationβ a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/sessionβ the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSessionupsertβ defaults tofalse; 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 lazy MongoDB::Cursor object. π¦ (The query is not immediately issued to the server β see below for the details, it's giving main character energy that just waits.)
The query can be customized using MongoDB::Cursor methods, or with an optional hash reference of options. iykyk β¨
Valid options include:
allowPartialResultsβ get partial results from a mongos if some shards are down (instead of throwing an error). no dramatic meltdown, just vibesbatchSizeβ the number of documents to return per batch.collationβ a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/commentβ attaches a comment to the query. πcursorTypeβ indicates the type of cursor to use. It must be one of three string values:'non_tailable'(the default),'tailable', and'tailable_await'.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 return. βmaxβ specify the exclusive upper bound for a specific index.maxAwaitTimeMSβ the maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. This only applies to acursorTypeof'tailable_await'; the option is otherwise ignored. (Note, this will be ignored for servers before version 3.2.) β³maxScanβ (DEPRECATED) maximum number of documents or index keys to scan.maxTimeMSβ the maximum amount of time to allow the query to run. (Note, this will be ignored for servers before version 2.6.)minβ specify the inclusive lower bound for a specific index.modifiersβ (DEPRECATED) a hash reference of dollar-prefixed query modifiers http://docs.mongodb.org/manual/reference/operator/query-modifier/ modifying the output or behavior of a query. Top-level options will always take precedence over corresponding modifiers. Supported modifiers include$comment,$hint,$maxScan,$maxTimeMS,$max,$min,$orderby,$returnKey,$showDiskLoc, and$snapshot. Some options may not be supported by newer server versions.noCursorTimeoutβ iftrue, 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.sessionβ the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSessionreturnKeyβ Only return the index field or fields for the results of the query https://docs.mongodb.com/manual/reference/operator/meta/returnKey/ πshowRecordIdβ modifies the output of a query by adding a field$recordIdhttps://docs.mongodb.com/manual/reference/method/cursor.showRecordId/ that uniquely identifies a document in a collection. π·οΈskipβ the number of documents to skip before returning.sortβ an ordered document defining the order in which to return matching documents. See the$orderbydocumentation https://docs.mongodb.com/manual/reference/operator/meta/orderby/ for examples.
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 theresultmethod is called on it or until an iterator method likenextis called. Performance will be better directly on a MongoDB::QueryResult object, bestie β do it this way:
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. one. singular. π«Ά
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. everything, the whole menu π
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:
collationβ a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/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.) β°sessionβ the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSessionsortβ an ordered document defining the order in which to return matching documents. If$orderbyalso exists in the modifiers document, the sort field overwrites$orderby. See docs for$orderbyhttp://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. it's literally just find_one with the id part already filled in for you, no cap π
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. so it's gone from the db but you still get to see it one last time π iconic exit, honestly
A hash reference of options may be provided. Valid keys include:
collationβ a document defining the collation for this operation. See docs for the format of the collation document here: https://docs.mongodb.com/master/reference/collation/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.sessionβ the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSessionsortβ an ordered document defining the order in which to return matching documents. See docs for$orderbyhttp://docs.mongodb.org/manual/reference/operator/meta/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). π like genuinely, none. this is a full replacement situation, not a little tweak situation.
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."collation"β a document defining the collation for this operation. See docs for the format of the collation document right here:https://docs.mongodb.com/master/reference/collation/."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:http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/."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'."session"β the session to use for these operations. If not supplied, will use an implicit session. For more information seeMongoDB::ClientSession."sort"β an ordered document defining the order in which to return matching documents. See docs for$orderbyhere: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 );
okay so bestie, you hand it a filter expression and a document full of update operators, and it updates one single document and hands it back to you β either as it was right before the update, or right after, your call. The default is 'before' π
The update document must contain only field-update operators (like $set). That's a hard requirement, not a suggestion, mmkay?
You can also pass a hash reference of options. The valid keys are:
"arrayFilters"β An array of filter documents that determines which array elements to modify for an update operation on an array field. Only available for MongoDB servers of version 3.6+. β¨"bypassDocumentValidation"β skips document validation, if enabled; this is ignored for MongoDB servers older than version 3.2."collation"β a document defining the collation for this operation. See docs for the format of the collation document right here:https://docs.mongodb.com/master/reference/collation/."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" in the MongoDB documentation for details:http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/."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'."session"β the session to use for these operations. If not supplied, will use an implicit session. For more information seeMongoDB::ClientSession."sort"β an ordered document defining the order in which to return matching documents. See docs for$orderbyhere: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.
π watch
Watches for changes on this collection-
So basically it runs an aggregation with an implicit initial $changeStream stage, and gives you back a MongoDB::ChangeStream result that you can iterate over to see what's poppin' 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, no cap. If you wanna respond to changes over a longer stretch of 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. iconic behaviour tbh.
The optional first argument must be an array-ref of aggregation pipeline documents: http://docs.mongodb.org/manual/core/aggregation-pipeline/. Each pipeline document must be a hash reference. Not all pipeline stages are supported after $changeStream β so don't get too creative, bestie.
The optional second argument is a hash reference with options:
"fullDocument"β The fullDocument to pass as an option to the$changeStreamstage. Allowed values:"default","updateLookup". Defaults to"default". When set to"updateLookup", the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. π"resumeAfter"β The logical starting point for this change stream. This value can be obtained from the"_id"field of a document returned by"next"inMongoDB::ChangeStream. Cannot be specified together with"startAtOperationTime"."maxAwaitTimeMS"β The maximum number of milliseconds for the server to wait before responding. β±οΈ"startAtOperationTime"β ABSON::Timestampspecifying at what point in time changes will start being watched. Cannot be specified together with"resumeAfter". Plain values will be coerced toBSON::Timestampobjects."session"β the session to use for these operations. If not supplied, will use an implicit session. For more information seeMongoDB::ClientSession.
See "aggregate" for more available options. π
See the manual section on Change Streams for general usage information on change streams: https://docs.mongodb.com/manual/changeStreams/.
See the Change Streams specification for details on change streams: https://github.com/mongodb/specifications/blob/master/source/change-streams.rst.
π₯ 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: http://docs.mongodb.org/manual/core/aggregation-pipeline/. Each pipeline document must be a hash reference.
Note: Some pipeline documents have ordered arguments, such as$sort. Be sure to provide these arguments usingTie::IxHash. E.g.:
{ '$sort' => Tie::IxHash->new( age => -1, posts => 1 ) }
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.)"collation"β a document defining the collation for this operation. See docs for the format of the collation document right here:https://docs.mongodb.com/master/reference/collation/."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.)"hint"β An index to use for this aggregation. (Only compatible with servers above version 3.6.) For more information, see the other aggregate options here:https://docs.mongodb.com/manual/reference/command/aggregate/index.html"session"β the session to use for these operations. If not supplied, will use an implicit session. For more information seeMongoDB::ClientSession.
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 newcollection>object to query the generated result collection. When$outis 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: http://docs.mongodb.org/manual/aggregation/.
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. Wanna count everything? Just use an empty hash reference as the filter, easy.
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. Save yourself, bestie.
A hash reference of options may be provided. Valid keys include:
"collation"β a document defining the collation for this operation. See docs for the format of the collation document right here:https://docs.mongodb.com/master/reference/collation/."hint"β specify an index to use; must be a string, array reference, hash reference orTie::IxHashobject. (Requires server version 3.6 or later.)"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."session"β the session to use for these operations. If not supplied, will use an implicit session. For more information seeMongoDB::ClientSession.
NOTE: When upgrading from the deprecated "count" method, some legacy operators are not supported and must be replaced:
$whereβ$expr(needs MongoDB 3.6+, no exceptions bestie) β¨$nearβ$geoWithinwith$centerπΊοΈ$nearSphereβ$geoWithinwith$centerSphereπ
π estimated_document_count
$count = $coll->estimated_document_count();
$count = $coll->estimated_document_count($options);
Gives you a vibes-based count of documents, straight off the collection metadata. It's an estimate, okay, not the whole truth β but it's fast and it ate. π
NOTE: this method does not support sessions or transactions. Periodt.
You can hand it a hash reference of options if you want. Valid keys include:
maxTimeMSβ the maximum amount of time in milliseconds to allow the command to run. (Heads up: this gets ignored for servers before version 2.6. π)
π¦ distinct
$result = $coll->distinct( $fieldname );
$result = $coll->distinct( $fieldname, $filter );
$result = $coll->distinct( $fieldname, $filter, $options );
Returns a MongoDB::QueryResult object that will hand you all the distinct values for a field name you specify. Iconic. π
The query may be limited by an optional filter expression β so you can be picky about it.
A hash reference of options may be provided. Valid keys include:
collationβ a document defining the collation for this operation. Go check the docs for the format of the collation document right here: <https://docs.mongodb.com/master/reference/collation/>. πmaxTimeMSβ the maximum amount of time in milliseconds to allow the command to run. (Again: ignored for servers before version 2.6. It's giving "please upgrade". π)sessionβ the session to use for these operations. If you don't supply one, it'll use an implicit session. For more info seeMongoDB::ClientSession. π«Ά
See the documentation for the distinct command <http://docs.mongodb.org/manual/reference/command/distinct/> for all the deets.
πΈ rename
$newcollection = $collection->rename("mynewcollection");
Renames the collection. Glow-up era. β¨
Careful: if a collection already exists with the new collection name, this method will throw an exception. No stealing names in this house.
A hashref of options may be provided.
Valid options include:
sessionβ the session to use for these operations. If not supplied, will use an implicit session. For more information seeMongoDB::ClientSession. π
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. It's giving "gone, deleted, never happened". π
π ordered_bulk
$bulk = $coll->ordered_bulk;
$bulk->insert_one( $doc1 );
$bulk->insert_one( $doc2 );
...
$result = $bulk->execute;
Returns a MongoDB::BulkWrite object so you can group write operations into fewer network round-trips. Efficiency queen. π
This method creates an ordered operation, meaning 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. Lowkey only works on the new stuff. π«
π 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. Chaos mode, but make it productive. π¦
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. Same deal as above. π
β bulk_write
$res = $coll->bulk_write( [ @requests ], $options )
This one is straight-up syntactic sugar: it builds and executes a bulk operation directly, so you don't have to use initialize_ordered_bulk or initialize_unordered_bulk to generate a MongoDB::BulkWrite object and then call methods on it. It returns a MongoDB::BulkWriteResponse object just like the MongoDB::BulkWrite execute method does. Convenience ate. π
The first argument must be an array reference of requests. A request is a pair of a MongoDB::Collection write method name (like insert_one, delete_many) plus an array reference of arguments for that method. You can give them 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 likeinitialize_ordered_bulk. When false, the bulk operation is executed likeinitialize_unordered_bulk. The default is true.sessionβ the session to use for these operations. If not supplied, will use an implicit session. For more information seeMongoDB::ClientSession. π«Ά
See MongoDB::BulkWrite for more details on bulk writes. Just a lil heads-up bestie: the legacy Bulk API method names differ slightly from MongoDB::Collection method names. Iykyk. π
π AUTHORS
- David Golden <david@mongodb.com>
- Rassi <rassi@mongodb.com>
- Mike Friedman <friedo@friedo.com>
- Kristina Chodorow <k.chodorow@gmail.com>
- Florian Ragwitz <rafl@debian.org>
π COPYRIGHT AND LICENSE
This software is Copyright (c) 2020 by MongoDB, Inc.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
and that's a wrap on the whole page, bestie!! π This beauty ships as perl v5.40.1, dated 2025-04-03, and it's the user-contributed Perl documentation for MongoD...lection(3pm). Go forth and query, you absolute main character. π
πΈβ¨
π¦ where this page comes from
- debian trixie: libmongodb-perl 2.2.2-3 Β· Apache-2.0
- ubuntu resolute: libmongodb-perl 2.2.2-3 Β· Apache-2.0
- ubuntu stonking: libmongodb-perl 2.2.2-3 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms