Cookie Notice

As far as I know, and as far as I remember, nothing in this page does anything with Cookies.

2014/01/31

Trying just MongoDB, and it works!

And it works!

  1. #!/usr/bin/perl  
  2.   
  3. use feature qw{ say state } ;  
  4. use strict ;  
  5. use warnings ;  
  6. use Data::Dumper ;  
  7. use MongoDBx::Class ;  
  8. use MongoDB ;  
  9.   
  10. my @movies ;  
  11. push @movies,  
  12.     {  
  13.     title           => 'Blade Runner',  
  14.     rating          => 'R',  
  15.     releaseYear     => '1982',  
  16.     hasCreditCookie => 1  
  17.     } ;  
  18. push @movies,  
  19.     {  
  20.     title           => 'Thor',  
  21.     rating          => 'PG-13',  
  22.     releaseYear     => '2011',  
  23.     hasCreditCookie => 1  
  24.     } ;  
  25.   
  26. {  
  27.     my $client     = MongoDB::MongoClient->new( host => 'localhost', port => 27017 ) ;  
  28.     my $database   = $client->get_database( 'test' ) ;  
  29.     my $collection = $database->get_collection( 'movies' ) ;  
  30.     my $movies     = $collection->find( ) ; # READ  
  31.     while ( my $movie = $movies->next ) { # would prefer for ( @$movies ) {} but oh well  
  32.         my $title = $movie->{ title } ? $movie->{ title } : 'none' ;  
  33.         my $releaseYear = $movie->{ releaseYear } ? $movie->{ releaseYear } : 'none' ;  
  34.         my $count = $movie->{ count } ? $movie->{ count } : 0 ;  
  35.         say qq{$title ($releaseYear) - $count } ;  
  36.         my $id = $movie->{ _id } ; # every mongodb record gets an _id  
  37.         $collection->remove( { _id => $id } ) if $title eq 'none' ; # DELETE  
  38.         $collection->update(  
  39.             { title => $title },  
  40.             { '$set' => { count => 1 + $count } }  
  41.             ) ; # UPDATE  
  42.         }  
  43.     #LADIES AND GENTLEMEN, WE HAVE CRUD!!!  
  44.     }  
  45. exit ;  
  46. {  
  47.     my $client     = MongoDB::MongoClient->new( host => 'localhost', port => 27017 ) ;  
  48.     my $database   = $client->get_database( 'test' ) ;  
  49.     my $collection = $database->get_collection( 'movies' ) ;  
  50.     my $data       = $collection->find( ) ;  
  51.     for my $movie ( @movies ) {  
  52.         say qq{$movie->{ title } ($movie->{ releaseYear })} ;  
  53.         $collection->insert( $movie ) ; # CREATE  
  54.         }  
  55.     }  

The lesson might be Don't Trust ORMs, Do It Yourself, but I hope that there's some reason to use these things.

No comments:

Post a Comment