MongoD...lection(3pm)

πŸ“¦
version 2.2.2 Β· 5 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

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 in MongoDB::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 in MongoDB::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_many bulk 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 individual insert_one calls. 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 in MongoDB::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 in MongoDB::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 in MongoDB::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 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. 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::ClientSession
  • upsert – defaults to false; if true, a new document will be added if one is not found by taking the filter expression and applying the update document operations to it prior to insertion.

find

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

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

Executes a query with a filter expression and returns a 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 vibes
  • batchSize – 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 a cursorType of '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 – if true, prevents the server from timing out a cursor after a period of inactivity. 😴
  • projection β€” a hash reference defining fields to return. See "limit fields to return http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/ " in the MongoDB documentation for details.
  • session β€” the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession
  • returnKey – 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 $recordId https://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 $orderby documentation 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 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, 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::ClientSession
  • sort – an ordered document defining the order in which to return matching documents. If $orderby also exists in the modifiers document, the sort field overwrites $orderby. See docs for $orderby http://docs.mongodb.org/manual/reference/operator/meta/orderby/

See also core documentation on querying: http://docs.mongodb.org/manual/core/read/ πŸ’œ


find_id

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

Executes a query with a filter expression of { _id => $id } and returns a single document. 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:


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 see MongoDB::ClientSession.
  • "sort" β€” an ordered document defining the order in which to return matching documents. See docs for $orderby here: 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 see MongoDB::ClientSession.
  • "sort" β€” an ordered document defining the order in which to return matching documents. See docs for $orderby here: 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 $changeStream stage. 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" in MongoDB::ChangeStream. Cannot be specified together with "startAtOperationTime".
  • "maxAwaitTimeMS" β€” The maximum number of milliseconds for the server to wait before responding. ⏱️
  • "startAtOperationTime" β€” A BSON::Timestamp specifying at what point in time changes will start being watched. Cannot be specified together with "resumeAfter". Plain values will be coerced to BSON::Timestamp objects.
  • "session" β€” the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::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 using Tie::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 see MongoDB::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 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 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 or Tie::IxHash object. (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 see MongoDB::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 β†’ $geoWithin with $center πŸ—ΊοΈ
  • $nearSphere β†’ $geoWithin with $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 see MongoDB::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 see MongoDB::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 like initialize_ordered_bulk. When false, the bulk operation is executed like initialize_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 see MongoDB::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>

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