Skip to content

Instantly share code, notes, and snippets.

@xdg
Last active December 23, 2015 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xdg/668f830da42f9c9f6be2 to your computer and use it in GitHub Desktop.
Save xdg/668f830da42f9c9f6be2 to your computer and use it in GitHub Desktop.
#!/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