{
    "mode": "perldoc",
    "parameter": "MongoDB::Tutorial",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3ATutorial/json",
    "generated": "2026-06-15T14:09:07Z",
    "sections": {
        "NAME": {
            "content": "MongoDB::Tutorial - Getting started with MongoDB\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version v2.2.2\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "The tutorial runs through the basic functionality of the MongoDB package. This is a good\nstarting point if you have never used MongoDB before.\n\nThe tutorial assumes that you are running a standalone MongoDB database server (i.e. not a\nreplica set) locally on the default port. You can download MongoDB from\n<http://www.mongodb.org>.\n",
            "subsections": []
        },
        "TERMINOLOGY": {
            "content": "Document-oriented database terms and their relational equivalents:\n\nDatabase\nDatabase\n\nCollection\nTable\n\nDocument\nRecord or row\n\nBSON::OID\nAutoincrementing primary key\n",
            "subsections": []
        },
        "PREAMBLE": {
            "content": "To use MongoDB, you'll usually just start with:\n\nuse MongoDB;\n\nThe MongoDB module loads most of the modules you'll need to interact with MongoDB:\n\n*   MongoDB::MongoClient\n\n*   MongoDB::Database\n\n*   MongoDB::Collection\n\n*   Query result classes like MongoDB::Cursor and MongoDB::QueryResult\n\n*   Write result classes like MongoDB::InsertOneResult and MongoDB::UpdateResult\n",
            "subsections": []
        },
        "CONNECTING": {
            "content": "To get started, we have to connect to the database server. Because it's running locally on the\ndefault port, we need not pass any parameters to the connect method.\n\nmy $client = MongoDB->connect();\n\nNow we we have a client connected to the MongoDB server. Next we need a database to work with,\nwe'll call it \"tutorial\". You need not do anything special to create the database, MongoDB will\ncreate it on the fly.\n\nmy $db = $client->getdatabase( 'tutorial' );\n\nThe last part of the preliminary setup is to choose a collection. We'll be using the \"users\"\ncollection to start out.\n\nmy $users = $db->getcollection( 'users' );\n\nAgain, there is no need to create the collection in advance, it will be created as needed.\n\nThe ns method is a short cut to get a MongoDB::Collection object direct from the client.\n\nmy $users = $client->ns(\"tutorial.users\");\n",
            "subsections": []
        },
        "CRUD": {
            "content": "",
            "subsections": [
                {
                    "name": "Creating Documents",
                    "content": "Inserting\nTo add a document to the collection, we use the insertone function. It takes a hash reference\nwhich is saved to the collection.\n\n$users->insertone( {\n\"name\" => \"Joe\",\n\"age\" => 52,\n\"likes\" => [qw/skiing math ponies/]\n});\n\nNow there is a user in the collection.\n\nBSON::OIDs\nWhen a document is inserted, it is given a \"id\" field if one does not already exist. By\ndefault, this field is a BSON::OID, 12 bytes that are guaranteed to be unique. The \"id\" field\nof the inserted document is returned in a MongoDB::InsertOneResult object by the \"insertone\"\nmethod.\n\nmy $result = $users->insertone({\"name\" => \"Bill\"});\nmy $id     = $result->insertedid;\n\nAn efficient way to insert documents is to send many at a time to the database by using\ninsertmany, which returns a MongoDB::InsertManyResult describing the documents inserted.\n\nmy $result = $users->insertmany(\\@manyusers);\n"
                },
                {
                    "name": "Retrieving Documents",
                    "content": "Queries\nTo retrieve documents that were saved to a collection, we can use the find method.\n\nmy $allusers = $users->find;\n\nTo query for certain criteria, say, all users named Joe, pass the query a hash with the\nkey/value pair you wish to match:\n\nmy $someusers = $users->find({\"name\" => \"Joe\"});\n\nYou can match array elements in your queries; for example, to find all users who like math:\n\nmy $geeks = $users->find({\"likes\" => \"math\"});\n\nThis being Perl, it is important to mention that you can also use regular expressions to search\nfor strings. If you wanted to find all users with the name John and all variations of said name,\nyou could do:\n\nmy $john = $users->find({\"name\" => qr/joh?n/i});\n\nSee \"Regular Expressions\" in MongoDB::DataTypes for more information.\n\nRanges\nAs queries are hashes, they use a special syntax to express comparisons, such as \"x < 4\". To\nmake the query a valid hash, MongoDB uses $-prefixed terms. For example, \"x < 4\" could be\nexpressed by:\n\nmy $doc321 = $collection->find({'x' => { '$lt' => 4 }});\n\nComparison operators can be combined to get a range:\n\nmy $doc32 = $collection->find({'x' => { '$gte' => 2, '$lt' => 4 }});\n\nCursors\n\"find\" returns a MongoDB::Cursor, which can be iterated over. It lazily loads results from the\ndatabase. The following prints all of the users' names:\n\nwhile (my $doc = $allusers->next) {\nprint $doc->{'name'}.\"\\n\";\n}\n\nA cursor can also be converted into an array of hash references. For example, to print the\n\"name\" field of the first result:\n\nmy @arr = $geeks->all;\nprint $arr[0]->{'name'}.\"\\n\";\n"
                },
                {
                    "name": "Updating Documents",
                    "content": "\"$\"-operators\nTo change a document after it has been saved to the database, you must pass updateone (or\nupdatemany to change many documents at once) two arguments. The first is a query argument,\nidentical to the previous section, to identify the document you want to change. The second is an\nargument that describes the change that you wish to make.\n\nThe change is described by $-prefixed descriptors. For example, to increment a field, we would\nwrite:\n\n$users->updateone({\"id\" => $id}, {'$inc' => {'age' => 1}});\n\nTo add an element to an array, we can use $push. So, to add an element to the \"likes\" array, we\nwrite:\n\n$users->updateone({\"id\" => $id}, {'$push' => {'likes' => 'reading'}});\n\nTo add a new field or change the type or value of an existing field, we use $set. For example,\nto change the \"name\" field to a username, we would say:\n\n$users->updateone({\"id\" => $id}, {'$set' => {'name' => 'joeschmoe'}});\n\nOptions\n\"updateone\" and \"updatemany\" do nothing if no document matches the query.\n\nSometimes we may want update to create an element if it does not already exist. This is called\nan 'upsert' (a combination of an update and an insert). For example, the same code could be used\nfor creating and updating a log document:\n\n$pageviews->updateone(\n{\"url\" => \"www.example.com\"},\n{'$inc' => {\"views\" => 1}},\n{'upsert' => 1}\n);\n\nIf the pageview counter for www.example.com did not exist yet, it would be created and the\n\"views\" field would be set to 1. If it did exist, the \"views\" field would be incremented.\n"
                },
                {
                    "name": "Deleting Documents",
                    "content": "To delete documents, we use the deleteone or deletemany methods. They take the same type of\nhash queries do:\n\n$users->deletemany({\"name\" => \"Joe\"});\n\nIt does not delete the collection, though (in that it will still appear if the user lists\ncollections in the database and the indexes will still exist). To remove a collection entirely,\ncall \"drop\":\n\n$users->drop;\n\n\"drop\" can also be used for whole databases:\n\n$db->drop;\n"
                }
            ]
        },
        "MONGODB BASICS": {
            "content": "",
            "subsections": [
                {
                    "name": "Database Commands",
                    "content": "There is a large number of useful database commands that can be called directly on $db with the\nruncommand method.\n\nFor example, you can use a database command to create a capped collection like so:\n\nuse boolean; # imports 'true' and 'false'\n\nmy $cmd = [\ncreate => \"posts\",\ncapped => true,\nsize   => 10240,\nmax    => 100\n];\n\n$db->runcommand($cmd);\n\nThis will create a capped collection called \"posts\" in the current database. It has a maximum\nsize of 10240 bytes and can contain up to 100 documents. The boolean module must be used\nwhenever the database expects an actual boolean argument (i.e. not \"1\" or \"0\").\n\nMongoDB expects commands to have key/value pairs in a certain order, so you must give arguments\nin an array reference (or Tie::IxHash object).\n"
                }
            ]
        },
        "NEXT STEPS": {
            "content": "Now that you know the basic syntax used by the Perl driver, you should be able to translate the\nJavaScript examples in the main MongoDB documentation (<http://www.mongodb.org>) into Perl.\n\nCheck out MongoDB::Examples for more examples.\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::Tutorial - Getting started with MongoDB",
    "flags": [],
    "examples": [],
    "see_also": []
}