MongoD...atabase(3pm)

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

πŸ’– NAME πŸ’–

MongoDB::Database β€” it's a MongoDB Database, bestie. That's the whole vibe. ✨

🌸 VERSION 🌸

version v2.2.2 β€” yes she's got a number and yes she's serving it πŸ’…

πŸ¦‹ SYNOPSIS πŸ¦‹

okay so here's the whole flow, watch this:

# get a Database object via MongoDB::MongoClient
my $db   = $client->get_database("foo");

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

# run a command on a database
my $res = $db->run_command([ismaster => 1]);

like... that's it. that's the entire client β†’ database β†’ collection pipeline and it's iconic. πŸŽ€

✨ DESCRIPTION ✨

So this class is literally the model of a MongoDB database, fr fr. You use it to construct MongoDB::Collection objects, and it also hands you the run_command method plus a bunch of lil convenience methods that are built on top of it. 🫢

Big note bestie: generally you never construct one of these directly with new. You call get_database on a MongoDB::MongoClient object and let it do the work. Main character energy, but from the client. πŸ‘‘

🌈 USAGE 🌈

😭 Error handling

Unless it's explicitly documented otherwise somewhere, literally every method throws exceptions if an error happens. The error types are documented in MongoDB::Error β€” go read that if you want the full lore.

To catch and handle those errors, the recommended modules are Try::Tiny and Safe::Isa:

use Try::Tiny;
use Safe::Isa; # provides $_isa

try {
    $db->run_command( @command )
}
catch {
    if ( $_->$_isa("MongoDB::DuplicateKeyError" ) {
        ...
    }
    else {
        ...
    }
};

And if you want failures to just retry themselves automatically, consider Try::Tiny::Retry. no cap, that one saves lives. πŸ™ˆ


πŸ’… ATTRIBUTES πŸ’…

name

The name of the database. simple. elegant. iconic.

read_preference

A MongoDB::ReadPreference object. You can initialize it with a string that corresponds to one of the valid read preference modes, or with a hash reference that'll get coerced into a brand new MongoDB::ReadPreference object. By default? It gets inherited from a MongoDB::MongoClient object. ✨

write_concern

A MongoDB::WriteConcern object. You can initialize it with a hash reference that will be coerced into a new MongoDB::WriteConcern object. And by default, can you guess? It's inherited from a MongoDB::MongoClient object. πŸŽ€

read_concern

A MongoDB::ReadConcern object. May be initialized with a hash reference or a string that gets coerced into the level of read concern.

By default it is, once again, inherited from a MongoDB::MongoClient object. (do you see the pattern, bestie 🌸)

max_time_ms

Specifies the maximum amount of time in milliseconds that the server should use for working on a query.

Note: this only gets used for server versions 2.6 or greater, because that's when the $maxTimeMS meta-operator was introduced. older servers? they don't know her. πŸ’€

bson_codec

An object that provides the encode_one and decode_one methods, like the ones from BSON. It may be initialized with a hash reference that will be coerced into a new BSON object. And yep β€” by default it is inherited from a MongoDB::MongoClient object. πŸ”₯


πŸ‘‘ METHODS πŸ‘‘

client

$client = $db->client;

Returns the MongoDB::MongoClient object associated with this object. your db knows its client, that's the relationship. 🫢

list_collections

$result = $coll->list_collections( $filter );
$result = $coll->list_collections( $filter, $options );

Returns a MongoDB::QueryResult object so you can iterate over collection description documents. Those documents contain "name" and "options" keys, like so:

use boolean;

{
    name => "my_capped_collection",
    options => {
        capped => true,
        size => 10485760,
    }
},

You can optionally pass a filter document, and then only the collection description documents matching that filter expression come back. See the listCollections command documentation <http://docs.mongodb.org/manual/reference/command/listCollections/> for more details on filtering for specific collections.

You can also hand over a hash reference of options. Valid keys include:

  • "batchSize" β€” the number of documents to return per batch.
  • "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.)
  • "nameOnly" β€” query and return names of the collections only. Defaults to false. (Note: this will be ignored for servers before version 4.0.)
  • "session" β€” the session to use for these operations. If not supplied, will use an implicit session. For more information see MongoDB::ClientSession.
NOTE: When using "nameOnly", the filter query must be empty or must only query the "name" field β€” otherwise no documents will be found. not even one. zero. nada. 😭

collection_names

my @collections = $database->collection_names;
my @collections = $database->collection_names( $filter );
my @collections = $database->collection_names( $filter, $options );

Returns the list of collections in this database. πŸŽ€

An optional filter document may be provided, which causes only collection description documents matching a filter expression to be returned. See the listCollections command documentation <http://docs.mongodb.org/manual/reference/command/listCollections/> for more details on filtering for specific collections.

A hashref of options may also 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.
Warning: if the number of collections is very large, this may return a very large result. Either pass an appropriate filter, or use list_collections to iterate over collections instead. do not just yolo this with a million collections, i'm begging 🫠

get_collection, coll

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

Returns a MongoDB::Collection for the given collection name within this database. 🌟

It takes an optional hash reference of options that get passed to the MongoDB::Collection constructor.

The coll method is an alias for get_collection.

get_gridfsbucket, gfs

my $grid = $database->get_gridfsbucket;
my $grid = $database->get_gridfsbucket($options);
my $grid = $database->gfs($options);

This method returns a MongoDB::GridFSBucket object for storing and retrieving files from the database. πŸ¦‹

It takes an optional hash reference of options that are passed to the MongoDB::GridFSBucket constructor.

See MongoDB::GridFSBucket for more information.

The gfs method is an alias for get_gridfsbucket.

drop

$database->drop;

Deletes the database. πŸ’€ gone. deleted. she's not coming back.

A hashref of options may also 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.

run_command

my $output = $database->run_command([ some_command => 1 ]);

my $output = $database->run_command(
    [ some_command => 1 ],
    { mode => 'secondaryPreferred' }
);

my $output = $database->run_command(
    [ some_command => 1 ],
    $read_preference,
    $options
);

This method runs a database command. The first argument must be a document with the command and its arguments. It should be given as an array reference of key-value pairs, or as a Tie::IxHash object with the command name as the first key. An error will be thrown if the command isn't an ordered document. so keep it ordered bestie ✨

By default, commands are run with a read preference of 'primary'. An optional second argument may specify an alternative read preference. If you give one, it must be a MongoDB::ReadPreference object or a hash reference that can be used to construct one.

A hashref of options may also 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 the output of the command (a hash reference) on success, or throws a MongoDB::DatabaseError exception if the command fails.

For a list of possible database commands, run:

my $commands = $db->run_command([listCommands => 1]);

There are a few examples of database commands in the "DATABASE COMMANDS" in MongoDB::Examples section. See also core documentation on database commands: <http://dochub.mongodb.org/core/commands>.

aggregate

Runs a query using the MongoDB 3.6+ 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.

The server supports several collection-less aggregation source stages like $currentOp and $listLocalSessions.

$result = $database->aggregate( [
    {
        "\$currentOp" => {
            allUsers => true,
        },
    },
] );

See Aggregation <http://docs.mongodb.org/manual/aggregation/> in the MongoDB manual for more information on how to construct aggregation queries.

watch

Watches for changes on this database. it's giving surveillance but make it ✨design✨.

Performs 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 database. This functionality is available since MongoDB 4.0.

my $stream = $db->watch();
my $stream = $db->watch( \@pipeline );
my $stream = $db->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. πŸ”

See "watch" in MongoDB::Collection for details on usage and available options.


🫢 AUTHORS 🫢

the legends themselves:

  • 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

okay and that's the whole page bestie, go forth and query responsibly 🌸

signing off from perl v5.40.1, dated 2025-04-03 β€” MongoD...atabase(3pm), User Contributed Perl Documentation, slay πŸ’…βœ¨πŸŽ€

πŸ“¦ where this page comes from