1MongoDB::Tutorial(3) User Contributed Perl Documentation MongoDB::Tutorial(3)
2
3
4
6 MongoDB::Tutorial - Getting started with MongoDB
7
9 version v2.2.2
10
12 The tutorial runs through the basic functionality of the MongoDB
13 package. This is a good starting point if you have never used MongoDB
14 before.
15
16 The tutorial assumes that you are running a standalone MongoDB database
17 server (i.e. not a replica set) locally on the default port. You can
18 download MongoDB from <http://www.mongodb.org>.
19
21 Document-oriented database terms and their relational equivalents:
22
23 Database
24 Database
25
26 Collection
27 Table
28
29 Document
30 Record or row
31
32 BSON::OID
33 Autoincrementing primary key
34
36 To use MongoDB, you'll usually just start with:
37
38 use MongoDB;
39
40 The MongoDB module loads most of the modules you'll need to interact
41 with MongoDB:
42
43 • MongoDB::MongoClient
44
45 • MongoDB::Database
46
47 • MongoDB::Collection
48
49 • Query result classes like MongoDB::Cursor and MongoDB::QueryResult
50
51 • Write result classes like MongoDB::InsertOneResult and
52 MongoDB::UpdateResult
53
55 To get started, we have to connect to the database server. Because
56 it's running locally on the default port, we need not pass any
57 parameters to the connect method.
58
59 my $client = MongoDB->connect();
60
61 Now we we have a client connected to the MongoDB server. Next we need
62 a database to work with, we'll call it "tutorial". You need not do
63 anything special to create the database, MongoDB will create it on the
64 fly.
65
66 my $db = $client->get_database( 'tutorial' );
67
68 The last part of the preliminary setup is to choose a collection.
69 We'll be using the "users" collection to start out.
70
71 my $users = $db->get_collection( 'users' );
72
73 Again, there is no need to create the collection in advance, it will be
74 created as needed.
75
76 The ns method is a short cut to get a MongoDB::Collection object direct
77 from the client.
78
79 my $users = $client->ns("tutorial.users");
80
82 Creating Documents
83 Inserting
84
85 To add a document to the collection, we use the insert_one function.
86 It takes a hash reference which is saved to the collection.
87
88 $users->insert_one( {
89 "name" => "Joe",
90 "age" => 52,
91 "likes" => [qw/skiing math ponies/]
92 });
93
94 Now there is a user in the collection.
95
96 BSON::OIDs
97
98 When a document is inserted, it is given a "_id" field if one does not
99 already exist. By default, this field is a BSON::OID, 12 bytes that
100 are guaranteed to be unique. The "_id" field of the inserted document
101 is returned in a MongoDB::InsertOneResult object by the "insert_one"
102 method.
103
104 my $result = $users->insert_one({"name" => "Bill"});
105 my $id = $result->inserted_id;
106
107 An efficient way to insert documents is to send many at a time to the
108 database by using insert_many, which returns a
109 MongoDB::InsertManyResult describing the documents inserted.
110
111 my $result = $users->insert_many(\@many_users);
112
113 Retrieving Documents
114 Queries
115
116 To retrieve documents that were saved to a collection, we can use the
117 find method.
118
119 my $all_users = $users->find;
120
121 To query for certain criteria, say, all users named Joe, pass the query
122 a hash with the key/value pair you wish to match:
123
124 my $some_users = $users->find({"name" => "Joe"});
125
126 You can match array elements in your queries; for example, to find all
127 users who like math:
128
129 my $geeks = $users->find({"likes" => "math"});
130
131 This being Perl, it is important to mention that you can also use
132 regular expressions to search for strings. If you wanted to find all
133 users with the name John and all variations of said name, you could do:
134
135 my $john = $users->find({"name" => qr/joh?n/i});
136
137 See "Regular Expressions" in MongoDB::DataTypes for more information.
138
139 Ranges
140
141 As queries are hashes, they use a special syntax to express
142 comparisons, such as "x < 4". To make the query a valid hash, MongoDB
143 uses $-prefixed terms. For example, "x < 4" could be expressed by:
144
145 my $doc321 = $collection->find({'x' => { '$lt' => 4 }});
146
147 Comparison operators can be combined to get a range:
148
149 my $doc32 = $collection->find({'x' => { '$gte' => 2, '$lt' => 4 }});
150
151 Cursors
152
153 "find" returns a MongoDB::Cursor, which can be iterated over. It
154 lazily loads results from the database. The following prints all of
155 the users' names:
156
157 while (my $doc = $all_users->next) {
158 print $doc->{'name'}."\n";
159 }
160
161 A cursor can also be converted into an array of hash references. For
162 example, to print the "name" field of the first result:
163
164 my @arr = $geeks->all;
165 print $arr[0]->{'name'}."\n";
166
167 Updating Documents
168 "$"-operators
169
170 To change a document after it has been saved to the database, you must
171 pass update_one (or update_many to change many documents at once) two
172 arguments. The first is a query argument, identical to the previous
173 section, to identify the document you want to change. The second is an
174 argument that describes the change that you wish to make.
175
176 The change is described by $-prefixed descriptors. For example, to
177 increment a field, we would write:
178
179 $users->update_one({"_id" => $id}, {'$inc' => {'age' => 1}});
180
181 To add an element to an array, we can use $push. So, to add an element
182 to the "likes" array, we write:
183
184 $users->update_one({"_id" => $id}, {'$push' => {'likes' => 'reading'}});
185
186 To add a new field or change the type or value of an existing field, we
187 use $set. For example, to change the "name" field to a username, we
188 would say:
189
190 $users->update_one({"_id" => $id}, {'$set' => {'name' => 'joe_schmoe'}});
191
192 Options
193
194 "update_one" and "update_many" do nothing if no document matches the
195 query.
196
197 Sometimes we may want update to create an element if it does not
198 already exist. This is called an 'upsert' (a combination of an update
199 and an insert). For example, the same code could be used for creating
200 and updating a log document:
201
202 $pageviews->update_one(
203 {"url" => "www.example.com"},
204 {'$inc' => {"views" => 1}},
205 {'upsert' => 1}
206 );
207
208 If the pageview counter for www.example.com did not exist yet, it would
209 be created and the "views" field would be set to 1. If it did exist,
210 the "views" field would be incremented.
211
212 Deleting Documents
213 To delete documents, we use the delete_one or delete_many methods.
214 They take the same type of hash queries do:
215
216 $users->delete_many({"name" => "Joe"});
217
218 It does not delete the collection, though (in that it will still appear
219 if the user lists collections in the database and the indexes will
220 still exist). To remove a collection entirely, call "drop":
221
222 $users->drop;
223
224 "drop" can also be used for whole databases:
225
226 $db->drop;
227
229 Database Commands
230 There is a large number of useful database commands that can be called
231 directly on $db with the run_command method.
232
233 For example, you can use a database command to create a capped
234 collection like so:
235
236 use boolean; # imports 'true' and 'false'
237
238 my $cmd = [
239 create => "posts",
240 capped => true,
241 size => 10240,
242 max => 100
243 ];
244
245 $db->run_command($cmd);
246
247 This will create a capped collection called "posts" in the current
248 database. It has a maximum size of 10240 bytes and can contain up to
249 100 documents. The boolean module must be used whenever the database
250 expects an actual boolean argument (i.e. not "1" or "0").
251
252 MongoDB expects commands to have key/value pairs in a certain order, so
253 you must give arguments in an array reference (or Tie::IxHash object).
254
256 Now that you know the basic syntax used by the Perl driver, you should
257 be able to translate the JavaScript examples in the main MongoDB
258 documentation (<http://www.mongodb.org>) into Perl.
259
260 Check out MongoDB::Examples for more examples.
261
263 • David Golden <david@mongodb.com>
264
265 • Rassi <rassi@mongodb.com>
266
267 • Mike Friedman <friedo@friedo.com>
268
269 • Kristina Chodorow <k.chodorow@gmail.com>
270
271 • Florian Ragwitz <rafl@debian.org>
272
274 This software is Copyright (c) 2020 by MongoDB, Inc.
275
276 This is free software, licensed under:
277
278 The Apache License, Version 2.0, January 2004
279
280
281
282perl v5.36.0 2022-07-22 MongoDB::Tutorial(3)