{
    "mode": "perldoc",
    "parameter": "MongoDB::Database",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3ADatabase/json",
    "generated": "2026-07-05T03:18:59Z",
    "synopsis": "# get a Database object via MongoDB::MongoClient\nmy $db   = $client->getdatabase(\"foo\");\n# get a Collection via the Database object\nmy $coll = $db->getcollection(\"people\");\n# run a command on a database\nmy $res = $db->runcommand([ismaster => 1]);",
    "sections": {
        "NAME": {
            "content": "MongoDB::Database - A MongoDB Database\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version v2.2.2\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "# get a Database object via MongoDB::MongoClient\nmy $db   = $client->getdatabase(\"foo\");\n\n# get a Collection via the Database object\nmy $coll = $db->getcollection(\"people\");\n\n# run a command on a database\nmy $res = $db->runcommand([ismaster => 1]);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This class models a MongoDB database. Use it to construct MongoDB::Collection objects. It also\nprovides the \"runcommand\" method and some convenience methods that use it.\n\nGenerally, you never construct one of these directly with \"new\". Instead, you call\n\"getdatabase\" on a MongoDB::MongoClient object.\n",
            "subsections": []
        },
        "USAGE": {
            "content": "",
            "subsections": [
                {
                    "name": "Error handling",
                    "content": "Unless otherwise explicitly documented, all methods throw exceptions if an error occurs. The\nerror types are documented in MongoDB::Error.\n\nTo catch and handle errors, the Try::Tiny and Safe::Isa modules are recommended:\n\nuse Try::Tiny;\nuse Safe::Isa; # provides $isa\n\ntry {\n$db->runcommand( @command )\n}\ncatch {\nif ( $->$isa(\"MongoDB::DuplicateKeyError\" ) {\n...\n}\nelse {\n...\n}\n};\n\nTo retry failures automatically, consider using Try::Tiny::Retry.\n"
                }
            ]
        },
        "ATTRIBUTES": {
            "content": "name\nThe name of the database.\n\nreadpreference\nA MongoDB::ReadPreference object. It may be initialized with a string corresponding to one of\nthe valid read preference modes or a hash reference that will be coerced into a new\nMongoDB::ReadPreference object. By default it will be inherited from a MongoDB::MongoClient\nobject.\n\nwriteconcern\nA MongoDB::WriteConcern object. It may be initialized with a hash reference that will be coerced\ninto a new MongoDB::WriteConcern object. By default it will be inherited from a\nMongoDB::MongoClient object.\n\nreadconcern\nA MongoDB::ReadConcern object. May be initialized with a hash reference or a string that will be\ncoerced into the level of read concern.\n\nBy default it will be inherited from a MongoDB::MongoClient object.\n\nmaxtimems\nSpecifies the maximum amount of time in milliseconds that the server should use for working on a\nquery.\n\nNote: this will only be used for server versions 2.6 or greater, as that was when the $maxTimeMS\nmeta-operator was introduced.\n\nbsoncodec\nAn object that provides the \"encodeone\" and \"decodeone\" methods, such as from BSON. It may be\ninitialized with a hash reference that will be coerced into a new BSON object. By default it\nwill be inherited from a MongoDB::MongoClient object.\n",
            "subsections": []
        },
        "METHODS": {
            "content": "client\n$client = $db->client;\n\nReturns the MongoDB::MongoClient object associated with this object.\n\nlistcollections\n$result = $coll->listcollections( $filter );\n$result = $coll->listcollections( $filter, $options );\n\nReturns a MongoDB::QueryResult object to iterate over collection description documents. These\nwill contain \"name\" and \"options\" keys like so:\n\nuse boolean;\n\n{\nname => \"mycappedcollection\",\noptions => {\ncapped => true,\nsize => 10485760,\n}\n},\n\nAn optional filter document may be provided, which cause only collection description documents\nmatching a filter expression to be returned. See the listCollections command documentation\n<http://docs.mongodb.org/manual/reference/command/listCollections/> for more details on\nfiltering for specific collections.\n\nA hash reference of options may be provided. Valid keys include:\n\n*   \"batchSize\" – the number of documents to return per batch.\n\n*   \"maxTimeMS\" – the maximum amount of time in milliseconds to allow the command to run. (Note,\nthis will be ignored for servers before version 2.6.)\n\n*   \"nameOnly\" - query and return names of the collections only. Defaults to false. (Note, this\nwill be ignored for servers before version 4.0)\n\n*   \"session\" - the session to use for these operations. If not supplied, will use an implicit\nsession. For more information see MongoDB::ClientSession\n\nNOTE: When using \"nameOnly\", the filter query must be empty or must only query the \"name\" field\nor else no documents will be found.\n\ncollectionnames\nmy @collections = $database->collectionnames;\nmy @collections = $database->collectionnames( $filter );\nmy @collections = $database->collectionnames( $filter, $options );\n\nReturns the list of collections in this database.\n\nAn optional filter document may be provided, which cause only collection description documents\nmatching a filter expression to be returned. See the listCollections command documentation\n<http://docs.mongodb.org/manual/reference/command/listCollections/> for more details on\nfiltering for specific collections.\n\nA hashref of options may also be provided.\n\nValid options include:\n\n*   \"session\" - the session to use for these operations. If not supplied, will use an implicit\nsession. For more information see MongoDB::ClientSession\n\nWarning: if the number of collections is very large, this may return a very large result. Either\npass an appropriate filter, or use \"listcollections\" to iterate over collections instead.\n\ngetcollection, coll\nmy $collection = $database->getcollection('foo');\nmy $collection = $database->getcollection('foo', $options);\nmy $collection = $database->coll('foo', $options);\n\nReturns a MongoDB::Collection for the given collection name within this database.\n\nIt takes an optional hash reference of options that are passed to the MongoDB::Collection\nconstructor.\n\nThe \"coll\" method is an alias for \"getcollection\".\n\ngetgridfsbucket, gfs\nmy $grid = $database->getgridfsbucket;\nmy $grid = $database->getgridfsbucket($options);\nmy $grid = $database->gfs($options);\n\nThis method returns a MongoDB::GridFSBucket object for storing and retrieving files from the\ndatabase.\n\nIt takes an optional hash reference of options that are passed to the MongoDB::GridFSBucket\nconstructor.\n\nSee MongoDB::GridFSBucket for more information.\n\nThe \"gfs\" method is an alias for \"getgridfsbucket\".\n\ndrop\n$database->drop;\n\nDeletes the database.\n\nA hashref of options may also be provided.\n\nValid options include:\n\n*   \"session\" - the session to use for these operations. If not supplied, will use an implicit\nsession. For more information see MongoDB::ClientSession\n\nruncommand\nmy $output = $database->runcommand([ somecommand => 1 ]);\n\nmy $output = $database->runcommand(\n[ somecommand => 1 ],\n{ mode => 'secondaryPreferred' }\n);\n\nmy $output = $database->runcommand(\n[ somecommand => 1 ],\n$readpreference,\n$options\n);\n\nThis method runs a database command. The first argument must be a document with the command and\nits arguments. It should be given as an array reference of key-value pairs or a Tie::IxHash\nobject with the command name as the first key. An error will be thrown if the command is not an\nordered document.\n\nBy default, commands are run with a read preference of 'primary'. An optional second argument\nmay specify an alternative read preference. If given, it must be a MongoDB::ReadPreference\nobject or a hash reference that can be used to construct one.\n\nA hashref of options may also be provided.\n\nValid options include:\n\n*   \"session\" - the session to use for these operations. If not supplied, will use an implicit\nsession. For more information see MongoDB::ClientSession\n\nIt returns the output of the command (a hash reference) on success or throws a\nMongoDB::DatabaseError exception if the command fails.\n\nFor a list of possible database commands, run:\n\nmy $commands = $db->runcommand([listCommands => 1]);\n\nThere are a few examples of database commands in the \"DATABASE COMMANDS\" in MongoDB::Examples\nsection. See also core documentation on database commands:\n<http://dochub.mongodb.org/core/commands>.\n\naggregate\nRuns a query using the MongoDB 3.6+ aggregation framework and returns a MongoDB::QueryResult\nobject.\n\nThe first argument must be an array-ref of aggregation pipeline\n<http://docs.mongodb.org/manual/core/aggregation-pipeline/> documents. Each pipeline document\nmust be a hash reference.\n\nThe server supports several collection-less aggregation source stages like $currentOp and\n$listLocalSessions.\n\n$result = $database->aggregate( [\n{\n\"\\$currentOp\" => {\nallUsers => true,\n},\n},\n] );\n\nSee Aggregation <http://docs.mongodb.org/manual/aggregation/> in the MongoDB manual for more\ninformation on how to construct aggregation queries.\n\nwatch\nWatches for changes on this database.\n\nPerform an aggregation with an implicit initial $changeStream stage and returns a\nMongoDB::ChangeStream result which can be used to iterate over the changes in the database. This\nfunctionality is available since MongoDB 4.0.\n\nmy $stream = $db->watch();\nmy $stream = $db->watch( \\@pipeline );\nmy $stream = $db->watch( \\@pipeline, \\%options );\n\nwhile (1) {\n\n# This inner loop will only run until no more changes are\n# available.\nwhile (my $change = $stream->next) {\n# process $change\n}\n}\n\nThe returned stream will not block forever waiting for changes. If you want to respond to\nchanges over a longer time use \"maxAwaitTimeMS\" and regularly call \"next\" in a loop.\n\nSee \"watch\" in MongoDB::Collection for details on usage and available options.\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "*   David Golden <david@mongodb.com>\n\n*   Rassi <rassi@mongodb.com>\n\n*   Mike Friedman <friedo@friedo.com>\n\n*   Kristina Chodorow <k.chodorow@gmail.com>\n\n*   Florian Ragwitz <rafl@debian.org>\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "This software is Copyright (c) 2020 by MongoDB, Inc.\n\nThis is free software, licensed under:\n\nThe Apache License, Version 2.0, January 2004\n",
            "subsections": []
        }
    },
    "summary": "MongoDB::Database - A MongoDB Database",
    "flags": [],
    "examples": [],
    "see_also": []
}