# MongoDB::Database - perldoc - [phpMan]

## NAME
    [MongoDB::Database](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3ADatabase/markdown) - A MongoDB Database

## VERSION
    version v2.2.2

## SYNOPSIS
        # get a Database object via [MongoDB::MongoClient](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AMongoClient/markdown)
        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]);

## DESCRIPTION
    This class models a MongoDB database. Use it to construct [MongoDB::Collection](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3ACollection/markdown) objects. It also
    provides the "run_command" method and some convenience methods that use it.

    Generally, you never construct one of these directly with "new". Instead, you call
    "get_database" on a [MongoDB::MongoClient](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AMongoClient/markdown) object.

## USAGE
### Error handling
    Unless otherwise explicitly documented, all methods throw exceptions if an error occurs. The
    error types are documented in [MongoDB::Error](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AError/markdown).

    To catch and handle errors, the [Try::Tiny](https://www.chedong.com/phpMan.php/perldoc/Try%3A%3ATiny/markdown) and [Safe::Isa](https://www.chedong.com/phpMan.php/perldoc/Safe%3A%3AIsa/markdown) modules are recommended:

        use [Try::Tiny](https://www.chedong.com/phpMan.php/perldoc/Try%3A%3ATiny/markdown);
        use [Safe::Isa](https://www.chedong.com/phpMan.php/perldoc/Safe%3A%3AIsa/markdown); # provides $_isa

        try {
            $db->run_command( @command )
        }
        catch {
            if ( $_->$_isa("[MongoDB::DuplicateKeyError](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3ADuplicateKeyError/markdown)" ) {
                ...
            }
            else {
                ...
            }
        };

    To retry failures automatically, consider using [Try::Tiny::Retry](https://www.chedong.com/phpMan.php/perldoc/Try%3A%3ATiny%3A%3ARetry/markdown).

## ATTRIBUTES
  name
    The name of the database.

  read_preference
    A [MongoDB::ReadPreference](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AReadPreference/markdown) 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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AReadPreference/markdown) object. By default it will be inherited from a [MongoDB::MongoClient](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AMongoClient/markdown)
    object.

  write_concern
    A [MongoDB::WriteConcern](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AWriteConcern/markdown) object. It may be initialized with a hash reference that will be coerced
    into a new [MongoDB::WriteConcern](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AWriteConcern/markdown) object. By default it will be inherited from a
    [MongoDB::MongoClient](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AMongoClient/markdown) object.

  read_concern
    A [MongoDB::ReadConcern](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AReadConcern/markdown) 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::MongoClient](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AMongoClient/markdown) object.

  max_time_ms
    Specifies the 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_codec
    An 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::MongoClient](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AMongoClient/markdown) object.

## METHODS
  client
        $client = $db->client;

    Returns the [MongoDB::MongoClient](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AMongoClient/markdown) object associated with this object.

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

    Returns a [MongoDB::QueryResult](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AQueryResult/markdown) object to iterate over collection description documents. These
    will contain "name" and "options" keys like so:

        use boolean;

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

    An optional filter document may be provided, which cause 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 hash reference of options may be provided. 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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AClientSession/markdown)

    NOTE: When using "nameOnly", the filter query must be empty or must only query the "name" field
    or else no documents will be found.

  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 cause 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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AClientSession/markdown)

    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.

  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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3ACollection/markdown) for the given collection name within this database.

    It takes an optional hash reference of options that are passed to the [MongoDB::Collection](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3ACollection/markdown)
    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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AGridFSBucket/markdown) object for storing and retrieving files from the
    database.

    It takes an optional hash reference of options that are passed to the [MongoDB::GridFSBucket](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AGridFSBucket/markdown)
    constructor.

    See [MongoDB::GridFSBucket](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AGridFSBucket/markdown) for more information.

    The "gfs" method is an alias for "get_gridfsbucket".

  drop
        $database->drop;

    Deletes the database.

    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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AClientSession/markdown)

  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 a [Tie::IxHash](https://www.chedong.com/phpMan.php/perldoc/Tie%3A%3AIxHash/markdown)
    object with the command name as the first key. An error will be thrown if the command is not an
    ordered document.

    By default, commands are run with a read preference of 'primary'. An optional second argument
    may specify an alternative read preference. If given, it must be a [MongoDB::ReadPreference](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AReadPreference/markdown)
    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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AClientSession/markdown)

    It returns the output of the command (a hash reference) on success or throws a
    [MongoDB::DatabaseError](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3ADatabaseError/markdown) 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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AExamples/markdown)
    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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AQueryResult/markdown)
    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.

    Perform an aggregation with an implicit initial $changeStream stage and returns a
    [MongoDB::ChangeStream](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AChangeStream/markdown) 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](https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3ACollection/markdown) for details on usage and available options.

## 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

