PinkElephantsOnParade
PinkElephantsOnParade

Reputation: 6592

MongoFiles, GridFS, and Perl

I've been using perl, MongoDB, and GridFS for some pet development, and wonder - is there anyway for perl to interface with Mongofiles (other than navigate there with system commands and call it that way, heh) - like..well...a cpan library? Or an extension of the current CPAN module for Mongo?

For an example of what I'd like to do:

I'd like to be able to store files into my mongoDB and retrieve files into my mongoDB - for example, from the command line, once I have navigated to the directory with mongofiles in it, I can execute

mongofiles put "C:\Users\Me\cool.txt"

And it will store the file into the DB! Let's say I DELETE cool.txt off of my drive. Now when I execute:

mongofiles get "C:\Users\Me\cool.txt"

It retrieves the file out of the DB and puts it in my directory! I just want to be able to access this mongofiles functionality from Perl. Even if that means having a copy of mongofiles in the directory with my script.

Upvotes: 2

Views: 1337

Answers (2)

Frederick Roth
Frederick Roth

Reputation: 2830

You want to use GridFS.

Here is the perl API for that: http://api.mongodb.org/perl/current/MongoDB/GridFS.html

Here an example for inserting:

use MongoDB::GridFS;

my $grid = $database->get_gridfs;
my $fh = IO::File->new("myfile", "r");
$grid->insert($fh, {"filename" => "mydbfile"});

And retrieving:

use MongoDB::GridFS::File;

my $outfile = IO::File->new("outfile", "w");
my $file = $grid->find_one({"filename" => "mydbfile"});;
$file->print($outfile);

Upvotes: 5

PinkElephantsOnParade
PinkElephantsOnParade

Reputation: 6592

Frederick provided me with the knowledge for this answer but for legacy's sake here is a full, working example...the likes of which cannot be found on the internet elsewhere:

#!usr/bin/perl

use MongoDB::GridFS;
use MongoDB;
use MongoDB::Database;
use MongoDB::OID;

my $conn = new MongoDB::Connection;
my $db   = $conn->test; #name of our local db is test...default of mongoDB
my $grid = $db->get_gridfs;
my $fh = IO::File->new("cool.txt", "r");
$grid->insert($fh, {"filename" => "test"});

Upvotes: 1

Related Questions