.\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "MongoDB::Tutorial 3pm" .TH MongoDB::Tutorial 3pm "2014-10-09" "perl v5.20.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" MongoDB::Tutorial \- Getting started with MongoDB .SH "VERSION" .IX Header "VERSION" version v0.705.0.0 .SH "DESCRIPTION" .IX Header "DESCRIPTION" The tutorial runs through the basic functionality of the MongoDB package. This is a good starting point if you have never used MongoDB before. .PP The tutorial assumes that you are running a MongoDB database server locally on the default port. You can download Mongo from . .SH "TERMINOLOGY" .IX Header "TERMINOLOGY" Document-oriented database terms and their relational equivalents: .IP "Database" 4 .IX Item "Database" Database .IP "Collection" 4 .IX Item "Collection" Table .IP "Document" 4 .IX Item "Document" Record or row .IP "MongoDB::OID" 4 .IX Item "MongoDB::OID" Autoincrementing primary key .SH "PREAMBLE" .IX Header "PREAMBLE" \&\f(CW\*(C`use MongoDB\*(C'\fR loads most of the packages you'll need to interact with MongoDB: MongoDB::MongoClient, MongoDB::Database, MongoDB::Collection, and MongoDB::Cursor. To use special Mongo data types (see MongoDB::DataTypes), you have to include them separately. So, usually, to use Mongo, you'll start with at least: .PP .Vb 2 \& use MongoDB; \& use MongoDB::OID; .Ve .SH "CONNECTING" .IX Header "CONNECTING" To get started, we have to connect to the database server. Because it's running locally on the default port, we need not pass any parameters to the MongoDB::MongoClient constructor: .PP .Vb 1 \& my $client = MongoDB::MongoClient\->new; .Ve .PP Now we're connected to the database server. Next we need a database to work with, we'll call it \*(L"tutorial\*(R". You need not do anything special to create the database, Mongo will create it on the fly. .PP .Vb 1 \& my $db = $client\->get_database( \*(Aqtutorial\*(Aq ); .Ve .PP The last part of the preliminary setup is to choose a collection. We'll be using the \*(L"users\*(R" collection to start out. .PP .Vb 1 \& my $users = $db\->get_collection( \*(Aqusers\*(Aq ); .Ve .PP Again, there is no need to create the collection in advance, it will be created as needed. .SH "CRUD" .IX Header "CRUD" .SS "Creating Documents" .IX Subsection "Creating Documents" \fIInserting\fR .IX Subsection "Inserting" .PP To add a document to the collection, we use the \f(CW\*(C`insert\*(C'\fR function. It takes a hash reference which is saved to the collection. .PP .Vb 3 \& $users\->insert({"name" => "Joe", \& "age" => 52, \& "likes" => [qw/skiing math ponies/]}); .Ve .PP Now there is a user in the collection. .PP \fIMongoDB::OIDs\fR .IX Subsection "MongoDB::OIDs" .PP When a document is inserted, it is given a \f(CW\*(C`_id\*(C'\fR field if one does not already exist. By default, this field is a MongoDB::OID, 12 bytes that are guaranteed to be unique. The \f(CW\*(C`_id\*(C'\fR field of the inserted document is returned by the \f(CW\*(C`insert\*(C'\fR method. .PP .Vb 1 \& my $id = $users\->insert({"name" => "Bill"}); .Ve .PP An efficient way to insert documents is to send many at a time to the database by using \f(CW\*(C`batch_insert\*(C'\fR, which returns an array of the \f(CW\*(C`_id\*(C'\fR fields of the documents inserted. .PP .Vb 1 \& my @ids = $users\->batch_insert(\e@many_users); .Ve .SS "Retrieving Documents" .IX Subsection "Retrieving Documents" \fIQueries\fR .IX Subsection "Queries" .PP To retrieve documents that were saved to a collection, we can use the \f(CW\*(C`find\*(C'\fR method. .PP .Vb 1 \& my $all_users = $users\->find; .Ve .PP To query for certain criteria, say, all users named Joe, pass the query a hash with the key/value pair you wish to match: .PP .Vb 1 \& my $some_users = $users\->find({"name" => "Joe"}); .Ve .PP You can match array elements in your queries; for example, to find all users who like math: .PP .Vb 1 \& my $geeks = $users\->find({"likes" => "math"}); .Ve .PP This being Perl, it is important to mention that you can also use regular expressions to search for strings. If you wanted to find all users with the name John and all variations of said name, you could do: .PP .Vb 1 \& my $john = $users\->find({"name" => qr/joh?n/i}); .Ve .PP See \*(L"Regular Expressions\*(R" in MongoDB::DataTypes for more information. .PP \fIRanges\fR .IX Subsection "Ranges" .PP As queries are hashes, they use a special syntax to express comparisons, such as \&\*(L"x < 4\*(R". To make the query a valid hash, Mongo uses $\-prefixed terms. For example, \*(L"x < 4\*(R" could be expressed by: .PP .Vb 1 \& my $doc321 = $collection\->find({\*(Aqx\*(Aq => { \*(Aq$lt\*(Aq => 4 }}); .Ve .PP Comparison operators can be combined to get a range: .PP .Vb 1 \& my $doc32 = $collection\->find({\*(Aqx\*(Aq => { \*(Aq$gte\*(Aq => 2, \*(Aq$lt\*(Aq => 4 }}); .Ve .PP \fICursors\fR .IX Subsection "Cursors" .PP \&\f(CW\*(C`find\*(C'\fR returns a MongoDB::Cursor, which can be iterated over. It lazily loads results from the database. The following prints all of the users' names: .PP .Vb 3 \& while (my $doc = $all_users\->next) { \& print $doc\->{\*(Aqname\*(Aq}."\en"; \& } .Ve .PP A cursor can also be converted into an array of hash references. For example, to print the \*(L"name\*(R" field of the first result: .PP .Vb 2 \& my @arr = $geeks\->all; \& print $arr[0]\->{\*(Aqname\*(Aq}."\en"; .Ve .SS "Updating Documents" .IX Subsection "Updating Documents" \fI\f(CI\*(C`$\*(C'\fI\-operators\fR .IX Subsection "$-operators" .PP To change a document after it has been saved to the database, you must pass \&\f(CW\*(C`update\*(C'\fR two arguments. The first is a query argument, identical to the previous section, to identify the document you want to change. The second is an argument that describes the change that you wish to make. .PP The change is described by $\-prefixed descriptors. For example, to increment a field, we would write: .PP .Vb 1 \& $users\->update({"_id" => $id}, {\*(Aq$inc\*(Aq => {\*(Aqage\*(Aq => 1}}); .Ve .PP To add an element to an array, we can use \f(CW$push\fR. So, to add an element to the \f(CW"likes"\fR array, we write: .PP .Vb 1 \& $users\->update({"_id" => $id}, {\*(Aq$push\*(Aq => {\*(Aqlikes\*(Aq => \*(Aqreading\*(Aq}}); .Ve .PP To add a new field or change the type or value of an existing field, we use \&\f(CW$set\fR. For example, to change the _id field to a username, we would say: .PP .Vb 1 \& $users\->update({"_id" => $id}, {\*(Aq$set\*(Aq => {\*(Aqname\*(Aq => \*(Aqjoe_schmoe\*(Aq}}); .Ve .PP \fIOptions\fR .IX Subsection "Options" .PP By default, \f(CW\*(C`update\*(C'\fR operates on one matching document, and does nothing if no document matches the query. There are two options available to change this behavior. .PP Suppose we want to add a \*(L"gift\*(R" field to everyone whose birthday it is today. One way would be to find every person whose birthday it was and iterate through the user documents, updating each one. However, it would be much faster and easier to update multiple documents at once. We can do this by using an optional third parameter with \f(CW\*(C`update\*(C'\fR: .PP .Vb 2 \& my $today = DateTime\->now; \& my $tomorrow = DateTime\->now\->set(\*(Aqday\*(Aq => $today\->day+1); \& \& $users\->update({"bday" => {\*(Aq$gte\*(Aq => $today, \*(Aq$lte\*(Aq => $tomorrow}}, \& {\*(Aq$set\*(Aq => {\*(Aqgift\*(Aq => $gift}}, \& {\*(Aqmultiple\*(Aq => 1}); .Ve .PP (This functionality was added in version 1.1.3 of the database and will not work in earlier versions.) Sometimes we may want update to create an element if it does not already exist. This is called an 'upsert' (a combination of an update and an insert). For example, the same code could be used for creating and updating a log document: .PP .Vb 3 \& $pageviews\->update({"url" => "www.example.com"}, \& {\*(Aq$inc\*(Aq => {"views" => 1}}, \& {\*(Aqupsert\*(Aq => 1}); .Ve .PP If the pageview counter for www.example.com did not exist yet, it would be created and the \*(L"views\*(R" field would be set to 1. If it did exist, the \*(L"views\*(R" field would be incremented. .SS "Deleting Documents" .IX Subsection "Deleting Documents" To delete documents, we use the \f(CW\*(C`remove\*(C'\fR method. It takes the same type of hash queries do: .PP .Vb 1 \& $users\->remove({"name" => "Joe"}); .Ve .PP Calling \f(CW\*(C`remove\*(C'\fR with no parameters removes all of the objects in a collection. It does not delete the collection, though (in that in that it will still appear if the user lists collections in the database and the indexes will still exist). To remove a collection entirely, call \f(CW\*(C`drop\*(C'\fR: .PP .Vb 1 \& $users\->drop; .Ve .PP \&\f(CW\*(C`drop\*(C'\fR can also be used for whole databases: .PP .Vb 1 \& $db\->drop; .Ve .SH "MONGODB BASICS" .IX Header "MONGODB BASICS" .SS "Database Commands" .IX Subsection "Database Commands" There are a large number of useful database commands that can be called directly with \f(CW$db\fR\->run_command. For example, to drop a collection, you can use: .PP .Vb 1 \& $db\->run_command({drop => $collection_name}); .Ve .PP \&\*(L"drop\*(R" only requires one key/value pair, but for commands that require multiple fields, Mongo expects key/value pairs to be in a certain order. It will not recognize the command if they are not ordered command name first. Thus, if you are running a database command, you should probably use Tie::IxHash instead of a normal hash (normal hashes are not ordered). .PP For example, you can use a database command to create a capped collection like so: .PP .Vb 4 \& my $cmd = Tie::IxHash\->new("create" => "posts", \& "capped" => boolean::true, \& "size" => 10240, \& "max" => 100); \& \& $db\->run_command($cmd); .Ve .PP This will create a capped collection called \*(L"posts\*(R" in the current database. It has a maximum size of 10240 bytes and can contain up to 100 documents. .SH "NEXT STEPS" .IX Header "NEXT STEPS" Now that you know the basic syntax used by the Perl driver, you should be able to translate the JavaScript examples in the main MongoDB documentation () into Perl. .PP Check out MongoDB::Examples for more examples. .SH "AUTHORS" .IX Header "AUTHORS" .IP "\(bu" 4 David Golden .IP "\(bu" 4 Mike Friedman .IP "\(bu" 4 Kristina Chodorow .IP "\(bu" 4 Florian Ragwitz .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is Copyright (c) 2014 by MongoDB, Inc.. .PP This is free software, licensed under: .PP .Vb 1 \& The Apache License, Version 2.0, January 2004 .Ve