{
    "mode": "perldoc",
    "parameter": "MongoDB::Examples",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/MongoDB%3A%3AExamples/json",
    "generated": "2026-06-12T19:47:18Z",
    "sections": {
        "NAME": {
            "content": "MongoDB::Examples - Some examples of MongoDB syntax\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version v2.2.2\n",
            "subsections": []
        },
        "MAPPING SQL TO MONGODB": {
            "content": "For developers familiar with SQL, the following chart should help you see how many common SQL\nqueries could be expressed in MongoDB.\n\nThese are Perl-specific examples of translating SQL queries to MongoDB's query language. To see\nthe mappings for JavaScript (or another language), see\n<http://docs.mongodb.org/manual/reference/sql-comparison/>.\n\nIn the following examples, $db is a MongoDB::Database object which was retrieved by using\n\"getdatabase\". See MongoDB::MongoClient, MongoDB::Database and MongoDB::Collection for more on\nthe methods you see below.\n\n\"CREATE TABLE USERS (a Number, b Number)\"\nImplicit, can be done explicitly.\n\n\"INSERT INTO USERS VALUES(1,1)\"\n$db->getcollection( 'users' )->insertone( { a => 1, b => 1 } );\n\n\"SELECT a,b FROM users\"\n$db->getcollection( 'users')->find( { } )->fields( { a => 1, b => 1 });\n\n\"SELECT * FROM users\"\n$db->getcollection( 'users' )->find;\n\n\"SELECT * FROM users WHERE age=33\"\n$db->getcollection( 'users' )->find( { age => 33 } )\n\n\"SELECT a,b FROM users WHERE age=33\"\n$db->getcollection( 'users' )->find( { age => 33 } )->fields( { a => 1, b => 1 });\n\n\"SELECT * FROM users WHERE age=33 ORDER BY name\"\n$db->getcollection( 'users' )->find( { age => 33 } )->sort( { name => 1 } );\n\n\"SELECT * FROM users WHERE age>33\"\n$db->getcollection( 'users' )->find( { age => { '$gt' => 33 } } );\n\n\"SELECT * FROM users WHERE age<33\"\n$db->getcollection( 'users' )->find( { age => { '$lt' => 33 } } );\n\n\"SELECT * FROM users WHERE name LIKE \"%Joe%\"\"\n$db->getcollection( 'users' )->find( { name => qr/Joe/ } );\n\n\"SELECT * FROM users WHERE name LIKE \"Joe%\"\"\n$db->getcollection( 'users' )->find( {name => qr/^Joe/ } );\n\n\"SELECT * FROM users WHERE age>33 AND age<=40\"\n$db->getcollection( 'users' )->find( { age => { '$gt' => 33, '$lte' => 40 } } );\n\n\"SELECT * FROM users ORDER BY name DESC\"\n$db->getcollection( 'users' )->find->sort( { name => -1 } );\n\n\"CREATE INDEX myindexname ON users(name)\"\nmy $indexes = $db->getcollection( 'users' )->indexes;\n$indexes->createone( [ name => 1 ] );\n\n\"CREATE INDEX myindexname ON users(name,ts DESC)\"\nmy $indexes = $db->getcollection( 'users' )->indexes;\n$indexes->createone( [ name => 1, ts => -1 ] );\n\n\"SELECT * FROM users WHERE a=1 and b='q'\"\n$db->getcollection( 'users' )->find( {a => 1, b => \"q\" } );\n\n\"SELECT * FROM users LIMIT 10 SKIP 20\"\n$db->getcollection( 'users' )->find->limit(10)->skip(20);\n\n\"SELECT * FROM users WHERE a=1 or b=2\"\n$db->getcollection( 'users' )->find( { '$or' => [ {a => 1 }, { b => 2 } ] } );\n\n\"SELECT * FROM users LIMIT 1\"\n$db->getcollection( 'users' )->find->limit(1);\n\n\"EXPLAIN SELECT * FROM users WHERE z=3\"\n$db->getcollection( 'users' )->find( { z => 3 } )->explain;\n\n\"SELECT DISTINCT lastname FROM users\"\n$db->getcollection( 'users' )->distinct( 'lastname' );\n\n\"SELECT COUNT(*y) FROM users\"\n$db->getcollection( 'users' )->countdocuments;\n\n\"SELECT COUNT(*y) FROM users where age > 30\"\n$db->getcollection( 'users' )->countdocuments( { \"age\" => { '$gt' => 30 } } );\n\n\"SELECT COUNT(age) from users\"\n$db->getcollection( 'users' )->countdocuments( { age => { '$exists' => 1 } } );\n\n\"UPDATE users SET a=1 WHERE b='q'\"\n$db->getcollection( 'users' )->updatemany( { b => \"q\" }, { '$set' => { a => 1 } } );\n\n\"UPDATE users SET a=a+2 WHERE b='q'\"\n$db->getcollection( 'users' )->updatemany( { b => \"q\" }, { '$inc' => { a => 2 } } );\n\n\"DELETE FROM users WHERE z=\"abc\"\"\n$db->getdatabase( 'users' )->deletemany( { z => \"abc\" } );\n",
            "subsections": []
        },
        "DATABASE COMMANDS": {
            "content": "If you do something in the MongoDB shell and you would like to translate it to Perl, the best\nway is to run the function in the shell without parentheses, which will print the source. You\ncan then generally translate the source into Perl fairly easily.\n\nFor example, suppose we want to use \"db.foo.validate\" in Perl. We could run:\n\n> db.foo.validate\nfunction (full) {\nvar cmd = {validate:this.getName()};\nif (typeof full == \"object\") {\nObject.extend(cmd, full);\n} else {\ncmd.full = full;\n}\nvar res = this.db.runCommand(cmd);\nif (typeof res.valid == \"undefined\") {\nres.valid = false;\nvar raw = res.result || res.raw;\nif (raw) {\nvar str = \"-\" + tojson(raw);\nres.valid = !(str.match(/exception/) || str.match(/corrupt/));\nvar p = /lastExtentSize:(\\d+)/;\nvar r = p.exec(str);\nif (r) {\nres.lastExtentSize = Number(r[1]);\n}\n}\n}\nreturn res;\n}\n\nNext, we can translate the important parts into Perl:\n\n$db->runcommand( [ validate => \"foo\" ] );\n",
            "subsections": [
                {
                    "name": "Find-one-and-modify",
                    "content": "The find-one-and-modify commands in MongoDB::Collection are similar to update (or remove), but\nwill return the modified document. They can be useful for implementing queues or locks.\n\nFor example, suppose we had a list of things to do, and we wanted to remove the highest-priority\nitem for processing. We could do a find and then a deleteone, but that wouldn't be atomic (a\nwrite could occur between the query and the remove). Instead, we could use findoneanddelete:\n\nmy $coll = $db->getcollection('todo');\nmy $nexttask = $todo->findoneanddelete(\n{}, # empty filter means any document\n{ sort => {priority => -1} },\n);\n\nThis will atomically find and pop the next-highest-priority task.\n\nSee <http://www.mongodb.org/display/DOCS/findAndModify+Command> for more details on\nfind-and-modify.\n"
                }
            ]
        },
        "AGGREGATION": {
            "content": "The aggregation framework is MongoDB's analogy for SQL GROUP BY queries, but more generic and\nmore powerful. An invocation of the aggregation framework specifies a series of stages in a\npipeline to be executed in order by the server. Each stage of the pipeline is drawn from one of\nthe following so-called \"pipeline operators\": $project, $match, $limit, $skip, $unwind, $group,\n$sort, and $geoNear.\n\nThe aggregation framework is the preferred way of performing most aggregation tasks. New in\nversion 2.2, it has largely obviated mapReduce\n<http://docs.mongodb.org/manual/reference/command/mapReduce/#dbcmd.mapReduce>, and group\n<http://docs.mongodb.org/manual/reference/command/group/#dbcmd.group>.\n\nSee the MongoDB aggregation framework documentation for more information\n(<http://docs.mongodb.org/manual/aggregation/>).\n\n$match and $group\nThe $group pipeline operator is used like GROUP BY in SQL. For example, suppose we have a number\nof local businesses stored in a \"business\" collection. If we wanted to find the number of\ncoffeeshops in each neighborhood, we could do:\n\nmy $out = $db->getcollection('business')->aggregate(\n[\n{'$match' => {'type' => 'coffeeshop'}},\n{'$group' => {'id' => '$neighborhood', 'numcoffeshops' => {'$sum' => 1}}}\n]\n);\n\nThe SQL equivalent is \"SELECT neighborhood, COUNT(*) FROM business GROUP BY neighborhood WHERE\ntype = 'coffeeshop'\". After executing the above aggregation query, $out will contain a\nMongoDB::QueryResult, allowing us to iterate through result documents such as the following:\n\n(\n{\n'id' => 'Soho',\n'numcoffeshops' => 23\n},\n{\n'id' => 'Chinatown',\n'numcoffeshops' => 14\n},\n{\n'id' => 'Upper East Side',\n'numcoffeshops' => 10\n},\n{\n'id' => 'East Village',\n'numcoffeshops' => 87\n}\n)\n\nNote that aggregate takes an array reference as an argument. Each element of the array is\ndocument which specifies a stage in the aggregation pipeline. Here our aggregation query\nconsists of a $match phase followed by a $group phase. Use $match to filter the documents in the\ncollection prior to aggregation. The \"id\" field in the $group stage specifies the key to group\nby; the \"$\" in '$neighborhood' indicates that we are referencing the name of a key. Finally, we\nuse the $sum operator to add one for every document in a particular neighborhood. There are\nother operators, such as $avg, $max, $min, $push, and $addToSet, which can be used in the $group\nphase and work much like $sum.\n\n$project and $unwind\nNow let's look at a more complex example of the aggregation framework that makes use of the\n$project and $unwind pipeline operators. Suppose we have a collection called 'courses' which\ncontains information on college courses. An example document in the collection looks like this:\n\n{\n'id' => 'CSCI0170',\n'name' => 'Computer Science 17',\n'description' => 'An Integrated Introduction to Computer Science',\n'instructorid' => 29823498,\n'instructorname' => 'A. Greenwald',\n'students' => [\n{ 'studentid' => 91736114, 'studentname' => 'D. Storch' },\n{ 'studentid' => 89100891, 'studentname' => 'J. Rassi' }\n]\n}\n\nWe wish to generate a report containing one document per student that indicates the courses in\nwhich each student is enrolled. The following call to \"aggregate\" will do the trick:\n\nmy $out = $db->getcollection('courses')->aggregate([\n{'$unwind' => '$students'},\n{'$project' => {\n'id' => 0,\n'course' => '$id',\n'studentid' => '$students.studentid',\n}\n},\n{'$group' => {\n'id' => '$studentid',\n'courses' => {'$addToSet' => '$course'}\n}\n}\n]);\n\nThe output documents will each have a student ID number and an array of the courses in which\nthat student is enrolled:\n\n(\n{\n'id' => 91736114,\n'courses' => ['CSCI0170', 'CSCI0220', 'APMA1650', 'HIST1230']\n},\n{\n'id' => 89100891,\n'courses' => ['CSCI0170', 'CSCI1670', 'CSCI1690']\n}\n)\n\nThe $unwind stage of the aggregation query \"peels off\" elements of the courses array one-by-one\nand places them in their own documents. After this phase completes, there is a separate document\nfor each (course, student) pair. The $project stage then throws out unnecessary fields and keeps\nthe ones we are interested in. It also pulls the student ID field out of its subdocument and\ncreates a top-level field with the key \"studentid\". Last, we group by student ID, using\n$addToSet in order to add the unique courses for each student to the \"courses\" array.\n\n$sort, $skip, and $limit\nThe $sort, $skip, and $limit pipeline operators work much like their companion methods in\nMongoDB::Cursor. Returning to the previous students and courses example, suppose that we were\nparticularly interested in the student with the ID that is numerically third-to-highest. We\ncould retrieve the course list for that student by adding $sort, $skip, and $limit phases to the\npipeline:\n\nmy $out = $db->getcollection('courses')->aggregate([\n{'$unwind' => '$students'},\n{'$project' => {\n'id' => 0,\n'course' => '$id',\n'studentid' => '$students.studentid',\n}\n},\n{'$group' => {\n'id' => '$studentid',\n'courses' => {'$addToSet' => '$course'}\n}\n},\n{'$sort' => {'id' => -1}},\n{'$skip' => 2},\n{'$limit' => 1}\n]);\n",
            "subsections": []
        },
        "QUERYING": {
            "content": "",
            "subsections": [
                {
                    "name": "Nested Fields",
                    "content": "MongoDB allows you to store deeply nested structures and then query for fields within them using\n*dot-notation*. For example, suppose we have a users collection with documents that look like:\n\n{\n\"userId\" => 12345,\n\"address\" => {\n\"street\" => \"123 Main St\",\n\"city\" => \"Springfield\",\n\"state\" => \"MN\",\n\"zip\" => \"43213\"\n}\n}\n\nIf we want to query for all users from Springfield, we can do:\n\nmy $cursor = $users->find({\"address.city\" => \"Springfield\"});\n\nThis will search documents for an \"address\" field that is a subdocument and a \"city\" field\nwithin the subdocument.\n"
                }
            ]
        },
        "UPDATING": {
            "content": "",
            "subsections": [
                {
                    "name": "Positional Operator",
                    "content": "In MongoDB 1.3.4 and later, you can use positional operator, \"$\", to update elements of an\narray. For instance, suppose you have an array of user information and you want to update a\nuser's name.\n\nA sample document in JavaScript:\n\n{\n\"users\" : [\n{\n\"name\" : \"bill\",\n\"age\" : 60\n},\n{\n\"name\" : \"fred\",\n\"age\" : 29\n},\n]\n}\n\nThe update:\n\n$coll->updateone({\"users.name\" => \"fred\"}, {'users.$.name' => \"george\"});\n\nThis will update the array so that the element containing \"name\" => \"fred\" now has \"name\" =>\n\"george\".\n"
                }
            ]
        },
        "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::Examples - Some examples of MongoDB syntax",
    "flags": [],
    "examples": [],
    "see_also": []
}