MongoD...utorial(3pm)
π¦ MongoDB::Tutorial(3pm) β bestie's guide to getting started
okay so this is the MongoDB::Tutorial page, from the User Contributed Perl Documentation crew π
β¨ VERSION β¨
version v2.2.2 β yes she's v2.2.2, iconic, no notes π
πΈ DESCRIPTION πΈ
So this tutorial walks you through the basic functionality of the MongoDB package, fr fr. If you have literally never touched MongoDB before, this is your starting point and it's giving beginner-friendly main character energy π«Ά
It assumes you're running a standalone MongoDB database server (i.e. not a replica set) locally, on the default port. You can download MongoDB from http://www.mongodb.org β
π TERMINOLOGY π
Document-oriented database terms and their relational equivalents β here's the translation chart, no cap:
- Database β Database
- Collection β Table
- Document β Record or row
- BSON::OID β Autoincrementing primary key
π§ PREAMBLE π§
To use MongoDB, you'll usually just start with this:
use MongoDB;
The MongoDB module loads most of the modules you'll need to interact with MongoDB:
- MongoDB::MongoClient
- MongoDB::Database
- MongoDB::Collection
- Query result classes like MongoDB::Cursor and MongoDB::QueryResult
- Write result classes like MongoDB::InsertOneResult and MongoDB::UpdateResult
π CONNECTING π
To get started, we have to connect to the database server. Because it's running locally on the default port, we don't need to pass any parameters to the connect method. Slay.
my $client = MongoDB->connect();
Now we have a client connected to the MongoDB server β¨ Next we need a database to work with β we'll call it "tutorial". You do not need to do anything special to create the database; MongoDB will create it on the fly. The way that just works π
my $db = $client->get_database( 'tutorial' );
The last part of the preliminary setup is to choose a collection. We'll be using the "users" collection to start out.
my $users = $db->get_collection( 'users' );
Again, there is no need to create the collection in advance β it will be created as needed π
The ns method is a short cut to get a MongoDB::Collection object direct from the client.
my $users = $client->ns("tutorial.users");
π₯ CRUD π₯
π Creating Documents
π Inserting
To add a document to the collection, we use the insert_one function. It takes a hash reference which is saved to the collection.
$users->insert_one( {
"name" => "Joe",
"age" => 52,
"likes" => [qw/skiing math ponies/]
});
Now there is a user in the collection π
π BSON::OIDs
When a document is inserted, it is given a "_id" field if one does not already exist. By default, this field is a BSON::OID β 12 bytes that are guaranteed to be unique. The "_id" field of the inserted document is returned in a MongoDB::InsertOneResult object by the "insert_one" method.
my $result = $users->insert_one({"name" => "Bill"});
my $id = $result->inserted_id;
An efficient way to insert documents is to send many at a time to the database by using insert_many, which returns a MongoDB::InsertManyResult describing the documents inserted.
my $result = $users->insert_many(\@many_users);
π Retrieving Documents
π Queries
To retrieve documents that were saved to a collection, we can use the find method.
my $all_users = $users->find;
To query for certain criteria β say, all users named Joe β pass the query a hash with the key/value pair you wish to match:
my $some_users = $users->find({"name" => "Joe"});
You can match array elements in your queries; for example, to find all users who like math:
my $geeks = $users->find({"likes" => "math"});
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:
my $john = $users->find({"name" => qr/joh?n/i});
See "Regular Expressions" in MongoDB::DataTypes for more information π¦
π Ranges
As queries are hashes, they use a special syntax to express comparisons, such as "x < 4". To make the query a valid hash, MongoDB uses $-prefixed terms. For example, "x < 4" could be expressed by:
my $doc321 = $collection->find({'x' => { '$lt' => 4 }});
Comparison operators can be combined to get a range:
my $doc32 = $collection->find({'x' => { '$gte' => 2, '$lt' => 4 }});
π Cursors
"find" returns a MongoDB::Cursor, which can be iterated over. It lazily loads results from the database β lowkey efficient π
The following prints all of the users' names:
while (my $doc = $all_users->next) {
print $doc->{'name'}."\n";
}
A cursor can also be converted into an array of hash references. For example, to print the "name" field of the first result:
my @arr = $geeks->all;
print $arr[0]->{'name'}."\n";
π Updating Documents
π "$"-operators
To change a document after it has been saved to the database, you must pass update_one (or update_many to change many documents at once) 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.
The change is described by $-prefixed descriptors. For example, to increment a field, we would write:
$users->update_one({"_id" => $id}, {'$inc' => {'age' => 1}});
To add an element to an array, we can use $push. So, to add an element to the "likes" array, we write:
$users->update_one({"_id" => $id}, {'$push' => {'likes' => 'reading'}});
To add a new field or change the type or value of an existing field, we use $set. For example, to change the "name" field to a username, we would say:
$users->update_one({"_id" => $id}, {'$set' => {'name' => 'joe_schmoe'}});
π Options
"update_one" and "update_many" do nothing if no document matches the query. Not me getting zero results back π
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:
$pageviews->update_one(
{"url" => "www.example.com"},
{'$inc' => {"views" => 1}},
{'upsert' => 1}
);
If the pageview counter for www.example.com did not exist yet, it would be created and the "views" field would be set to 1. If it did exist, the "views" field would be incremented. Upsy-daisy β¨
π Deleting Documents
To delete documents, we use the delete_one or delete_many methods. They take the same type of hash queries do:
$users->delete_many({"name" => "Joe"});
It does not delete the collection, though (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 "drop":
$users->drop;
"drop" can also be used for whole databases:
$db->drop;
π MONGODB BASICS π
π Database Commands
There is a large number of useful database commands that can be called directly on $db with the run_command method.
For example, you can use a database command to create a capped collection like so:
use boolean; # imports 'true' and 'false'
my $cmd = [
create => "posts",
capped => true,
size => 10240,
max => 100
];
$db->run_command($cmd);
This will create a capped collection called "posts" in the current database. It has a maximum size of 10240 bytes and can contain up to 100 documents. The boolean module must be used whenever the database expects an actual boolean argument (i.e. not "1" or "0") β do not skip this bestie, it really does matter π«Ά
MongoDB expects commands to have key/value pairs in a certain order, so you must give arguments in an array reference (or Tie::IxHash object).
π 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 (http://www.mongodb.org) into Perl.
Check out MongoDB::Examples for more examples. Go forth and slay π
π AUTHORS π
- David Golden <david@mongodb.com>
- Rassi <rassi@mongodb.com>
- Mike Friedman <friedo@friedo.com>
- Kristina Chodorow <k.chodorow@gmail.com>
- Florian Ragwitz <rafl@debian.org>
π COPYRIGHT AND LICENSE π
This software is Copyright (c) 2020 by MongoDB, Inc.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
and that's the whole page, bestie π¦ this was MongoD...utorial(3pm) from perl v5.40.1, dated 2025-04-03 β periodt, go build something cute πβ¨
π¦ where this page comes from
- debian trixie: libmongodb-perl 2.2.2-3 Β· Apache-2.0
- ubuntu resolute: libmongodb-perl 2.2.2-3 Β· Apache-2.0
- ubuntu stonking: libmongodb-perl 2.2.2-3 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms