Skip to content

Instantly share code, notes, and snippets.

@xdg xdg/compressed-gridfs.pl Secret
Last active Dec 23, 2015

Embed
What would you like to do?
#!/usr/bin/env perl
use v5.10;
use strict;
use warnings;
use Path::Tiny;
use MongoDB;
use IO::Compress::Gzip qw/gzip $GzipError/;
use IO::Uncompress::Gunzip qw/gunzip $GunzipError/;
# connect to MongoDB on localhost
my $mc = MongoDB->connect();
# get the MongoDB::GridFSBucket object, with majority read/write concerns
my $gfs = $mc->db("test")->gfs;
# drop the GridFS bucket for this demo
$gfs->drop;
# print info on file to upload
my $file = path("big.txt");
say "local $file is " . ( -s $file ) . " bytes";
# open a handle for uploading
my $up_fh = $gfs->open_upload_stream("$file")->fh;
# compress and upload file
gzip $file->openr_raw => $up_fh
or die $GzipError;
# flush data to GridFS
my $doc = $up_fh->close;
say "gridfs $file is " . $doc->{length} . " bytes";
# download and uncompress file
my $copy = path("big2.txt");
gunzip $gfs->open_download_stream( $doc->{_id} )->fh => $copy->openw_raw
or die $GunzipError;
say "copied $copy is " . ( -s $copy ) . " bytes";
# report compression ratio
printf("compressed was %d%% of original\n", 100 * $doc->{length} / -s $file );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.