1MongoDB::Tutorial(3)  User Contributed Perl Documentation MongoDB::Tutorial(3)
2
3
4

NAME

6       MongoDB::Tutorial - Getting started with MongoDB
7

DESCRIPTION

9       The tutorial runs through the basic functionality of the MongoDB
10       package.  This is a good starting point if you have never used MongoDB
11       before.
12
13       The tutorial assumes that you are running a Mongo database server
14       locally on the default port.  You can download Mongo from
15       <http://www.mongodb.org>.
16

TERMINOLOGY

18       Document-oriented database terms and their relational equivalents:
19
20       Database
21           Database
22
23       Collection
24           Table
25
26       Document
27           Record or row
28
29       MongoDB::OID
30           Autoincrementing primary key
31

PREAMBLE

33       The MongoDB package load MongoDB::Connection, MongoDB::Database,
34       MongoDB::Collection, and MongoDB::Cursor.  To use special Mongo data
35       types (see MongoDB::DataTypes), you have to include them separately.
36       So, usually, to use Mongo, you'll start with at least:
37
38           use MongoDB;
39           use MongoDB::OID;
40

CONNECTING

42       To get started, we have to connect to the database server.  Because
43       it's running locally on the default port, we need not pass any
44       parameters to the MongoDB::Connection constructor:
45
46           my $conn = MongoDB::Connection->new;
47
48       Now we're connected to the database server.  Next we need a database to
49       work with, we'll call it "tutorial".  You need not do anything special
50       to create the database, Mongo will create it on the fly.
51
52           my $db = $conn->tutorial;
53
54       The last part of the preliminary setup is to choose a collection.
55       We'll be using the "users" collection to start out.
56
57           my $users = $db->users;
58
59       Again, there is no need to create the collection in advance, it will be
60       created as needed.
61

CRUD

63   Creating Documents
64       Before you get started with MongoDB, it is important to know that, by
65       default, MongoDB does not return a response from writes (inserts,
66       updates, and deletes).  If you would like to know if the insert
67       succeeded or failed, use the "safe" option.  For more information on
68       this, see <http://www.mongodb.org/display/DOCS/Last+Error+Commands> for
69       details.
70
71       Inserting
72
73       To add a document to the collection, we use the "insert" function.  It
74       takes a hash which is saved to the collection.
75
76           $users->insert({"name" => "Joe",
77               "age" => 52,
78               "likes" => [qw/skiing math ponies/]});
79
80       Now there is a user in the collection.
81
82       MongoDB::OIDs
83
84       When a document is inserted, it is given a "_id" field if one does not
85       already exist.  By default, this field is a MongoDB::OID, 12 bytes that
86       are guaranteed to be unique. The "_id" field of the inserted document
87       is returned by the "insert" method.
88
89           my $id = $users->insert({"name" => "Bill"});
90
91       An efficient way to insert documents is to send many at a time to the
92       database by using "batch_insert", which returns an array of the "_id"
93       fields of the documents inserted.
94
95           @ids = $users->batch_insert(\@fifty_users);
96
97   Retrieving Documents
98       Queries
99
100       To retrieve documents that were saved to a collection, we can use the
101       "find" method.
102
103           my $all_users = $users->find;
104
105       To query for certain criteria, say, all users named Joe, pass the query
106       a hash with the key/value pair you wish to match:
107
108           my $some_users = $users->find({"name" => "Joe"});
109
110       You can match array elements in your querys; for example, to find all
111       users who like math:
112
113           my $geeks = $users->find({"likes" => "math"});
114
115
116
117       This being Perl, it is important to mention that you can also use
118       regular expressions to search for strings.  If you wanted to find all
119       users with the name John and all variations of said name, you could do:
120
121           my $john = $users->find({"name" => qr/joh?n/i});
122
123       See "Regular Expressions" in MongoDB::DataTypes for more information.
124
125       Ranges
126
127       As queries are hashes, they use a special syntax to express
128       comparisons, such as "x < 4".  To make the query a valid hash, Mongo
129       uses $-prefixed terms.  For example, "x < 4" could be expressed by:
130
131           my $doc321 = $collection->query({'x' => { '$lt' => 4 }});
132
133       Comparison operators can be combined to get a range:
134
135           my $doc32 = $collection->query({'x' => { '$gte' => 2, '$lt' => 4 }});
136
137       Cursors
138
139       "query" returns a MongoDB::Cursor, which can be iterated over.  It
140       lazily loads results from the database.  The following prints all of
141       the users' names:
142
143           while (my $doc = $all_users->next) {
144               print $doc->{'name'}."\n";
145           }
146
147       A cursor can also be converted into an array of hash references.  For
148       example, to print the "name" field of the first result:
149
150           my @arr = $geeks->all;
151           print $arr[0]->{'name'}."\n";
152
153   Updating Documents
154       "$"-operators
155
156       To change a document after it has been saved to the database, you must
157       pass "update" two arguments.  The first is a query argument, identical
158       to the previous section, to identify the document you want to change.
159       The second is an argument that describes the change that you wish to
160       make.
161
162       The change is described by $-prefixed descriptors.  For example, to
163       increment a field, we would write:
164
165           $users->update({"_id" => $id}, {'$inc' => {'age' => 1}});
166
167       To add an element to an array, we can use $push.  So, to add an element
168       to the "likes" array, we write:
169
170           $users->update({"_id" => $id}, {'$push' => {'likes' => 'reading'}});
171
172       To add a new field or change the type or value of an existing field, we
173       use $set.  For example, to change the _id field to a username, we would
174       say:
175
176           $users->update({"_id" => $id}, {'$set' => {'_id' => 'joe_schmoe'}});
177
178       Options
179
180       By default, "update" operates on one matching document, and does
181       nothing if no document matches the query.  There are two options
182       available to change this behavior.
183
184       Suppose we want to add a "gift" field to everyone whose birthday it is
185       today.  One way would be to find every person whose birthday it was and
186       iterate through the user documents, updating each one.  However, it
187       would be much faster and easier to update multiple documents at once.
188       We can do this by using an optional third parameter with "update":
189
190           my $today = DateTime->now;
191           my $tomorrow = DateTime->now->set('day' => $today->day+1);
192
193           $users->update({"bday" => {'$gte' => $today, '$lte' => $tomorrow}},
194               {'$set' => {'gift' => $gift}},
195               {'multiple' => 1});
196
197       (This functionality was added in version 1.1.3 of the database and will
198       not work in earlier versions.) Sometimes we may want update to create
199       an element if it does not already exist.  This is called an 'upsert'
200       (as it is a combination of an update and an insert).  For example, the
201       same code could be used for creating and updating a log document:
202
203           $pageviews->update({"url" => "www.example.com"},
204               {'$inc' => {"views" => 1}},
205               {'upsert' => 1});
206
207       If the pageview counter for www.example.com did not exist yet, it would
208       be created and the "views" field would be set to 1.  If it did exist,
209       the "views" field would be incremented.
210
211   Deleting Documents
212       To delete documents, we use the "remove" method.  It takes the same
213       type of hash queries do:
214
215           $users->remove({"name" => "Joe"});
216
217       Calling "remove" with no parameters removes all of the objects in a
218       collection.  It does not delete the collection, though (in that in that
219       it will still appear if the user lists collections in the database and
220       the indexes will still exist).  To remove a collection entirely, call
221       "drop":
222
223           $users->drop;
224
225       "drop" can also be used for whole databases:
226
227           $db->drop;
228

MONGO BASICS

230   Database Commands
231       There are a large number of useful database commands that can be called
232       directly with $db->run_command. For example, to drop a collection, you
233       can use:
234
235           $db->run_command({drop => $collection_name});
236
237       "drop" only requires one key/value pair, but for commands that require
238       multiple fields, Mongo expects key/value pairs to be in a certain
239       order. It will not recognize the command if they are not ordered
240       command name first. Thus, if you are running a database command, you
241       should probably use Tie::IxHash instead of a normal hash (normal hashes
242       are not ordered).
243
244       For example, you can use a database command to create a capped
245       collection like so:
246
247           my $cmd = Tie::IxHash->new("create" => "posts",
248               "capped" => boolean::true,
249               "size" => 10240,
250               "max" => 100);
251
252           $db->run_command($cmd);
253
254       This will create a capped collection called "posts" in the current
255       database.  It has a maximum size of 10240 bytes and can contain up to
256       100 documents.
257

NEXT STEPS

259       Now that you know the basic syntax used by the Perl driver, you should
260       be able to translate the JavaScript examples in the main MongoDB
261       documentation (<http://www.mongodb.org>) into Perl.
262
263       If there's anything else you'd like to see as part of the tutorial or
264       documentation in general, please contact kristina@mongodb.org.
265
266
267
268perl v5.12.3                      2010-11-19              MongoDB::Tutorial(3)
Impressum