Camelia

MongoDB with Perl 6 on Linux

MongoDB is the leading Open Source document database. In this article we'll see how to use it in a Perl 6 script using the Rakudo Star distribution.

Note! This site is about Perl 6.
If you are looking for a solution for Perl 5, please check out the Perl 5 tutorial.

Install MongoDB on Ubuntu Linux

Usually it is a good idea to update your Ubuntu with the latest security and other important fixes:

$ sudo apt-get update
$ sudo apt-get -y upgrade

Then we can install the MongoDB server packaged by the Debian/Ubuntu developers:

$ apt-get -y install mongodb

Then we install gcc and make needed to compile some Perl 6 modules that are written in C.

$ sudo apt-get -y install make gcc

We also install libssl-dev which is required by one of the dependencies of the MongoDB driver.

$ sudo apt-get -y install libssl-dev

Then we can install the MongoDB driver using zef:

zef install MongoDB

Check MongoDB manually

Before we try to access it using Perl 6, let's make sure the MongoDB server is already running. Type mongo in the Linux terminal. It will print something like this:

MongoDB shell version: 3.2.11
connecting to: test

potentially followed by some warnings. For now we can disregard the warnings.

At the end we can see the prompt:

>

there we can type in

> show dbs

that will print something like

local  0.000GB

You can type in help and play around with MongoDB manually, but for our purposes this was enough. Let's leave the MongoDB client by typing exit or pressing Ctrl-D.

Insert document into MongoDB

examples/mongodb_insert.pl

use BSON::Document;
use MongoDB::Client;

sub MAIN($name) {
    my $client = MongoDB::Client.new(:uri('mongodb://'));
    my $database = $client.database('myProject');
    
    my $req = BSON::Document.new: (
      insert => 'people',
      documents => [
        ( 
          name => $name,
        ),
      ]
    );
    $database.run-command($req);
}

First we create a MongoDB::Client object that connects to the local MongoDB server.

Then using the client we retrieve an object representing the database. This database might not even exist at this point.

Then instead of getting a collection object as it is done in some other implementation of the MongoDB client, we create a BSON document that includes the command and name of the collection (insert => 'people') and the documents we would like to insert. In this case a simple key-value pair for which we got the value from the command line.

The run-command actually executes the command and insert the document in the given collection of the given database. If either the collection or the database did not exist, then they will be created.

Try the following:

perl6 mongodb_insert.pl "Marcel Timmerman"
perl6 mongodb_insert.pl "Larry Wall"

Find documents in MongoDB

examples/mongodb_find.pl

use MongoDB::Client;

my $client = MongoDB::Client.new(:uri('mongodb://'));
my $database = $client.database('myProject');
my $collection = $database.collection('people');
my $cursor = $collection.find();

while $cursor.fetch -> $d {
  say "Name: ", $d<name>;
}

To retrieve data from MongoDB we need to call the find method of a collection. It returns a MongoDB::Cursor object that we can use to iterate over the returned documents.

Try the following:

perl6 mongodb_find.pl

Name: Larry Wall
Name: Marcel Timmerman

Fully annotated version of insert and find

Perl 6 allows us to annotate the variables with types that will be then used to enforce type-checking. The following examples are the "fully annotated" versions of the above code.

insert

examples/mongodb_insert_with_types.pl

use BSON::Document;
use MongoDB::Client;
use MongoDB::Database;

sub MAIN($name) {
    my MongoDB::Client $client .= new(:uri('mongodb://'));
    my MongoDB::Database $database = $client.database('myProject');
    
    my BSON::Document $req .= new: (
      insert => 'people',
      documents => [
        BSON::Document.new((
          name => $name,
        )),
      ]
    );
    my BSON::Document $doc = $database.run-command($req);
}

find

examples/mongodb_find_with_types.pl

use BSON::Document;
use MongoDB::Client;
use MongoDB::Database;
use MongoDB::Collection;
use MongoDB::Cursor;

my MongoDB::Client $client .= new(:uri('mongodb://'));
my MongoDB::Database $database = $client.database('myProject');

my MongoDB::Collection $collection = $database.collection('people');
my MongoDB::Cursor $cursor = $collection.find();

while $cursor.fetch -> BSON::Document $d {
  say "Name: ", $d<name>;
}

Inspect manually and delete the MongoDB database

If you'd like to start from scratch you can use the MongoDB client to delete the content of the newly created database:

Connect to MongoDB:

$ mongo

List the Databases:

> show dbs
local      0.000GB
myProject  0.000GB

Switch to the database you'd like to delete:

> use myProject

Before you delete the database you might want to inspect it manually:

> db.people.find()

{ "_id" : ObjectId("595f844e31d4268291806ee6"), "name" : "Larry Wall" }
{ "_id" : ObjectId("595f860a31d4268291806ee7"), "name" : "Marcel Timmerman" }

Delete the database:

> db.dropDatabase()
{ "dropped" : "myProject", "ok" : 1 }


The Perl 6 Tricks and Treats newsletter has been around for a while. If you are interested to get special notification when there is new content on this site, it is the best way to keep track:
Email:
Full name:
This is a newsletter temporarily running on my personal site (szabgab.com) using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2017-07-08



Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus
Suggest a change
Elapsed time: 2.305766

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.
Email:
Name: