#!/usr/bin/perl
use feature qw{ say state } ;
use strict ;
use warnings ;
use Data::Dumper ;
use MongoDBx::Class ;
use MongoDB ;
my @movies ;
push @movies,
{
title => 'Blade Runner',
rating => 'R',
releaseYear => '1982',
hasCreditCookie => 1
} ;
push @movies,
{
title => 'Thor',
rating => 'PG-13',
releaseYear => '2011',
hasCreditCookie => 1
} ;
{
my $client = MongoDB::MongoClient->new( host => 'localhost', port => 27017 ) ;
my $database = $client->get_database( 'test' ) ;
my $collection = $database->get_collection( 'movies' ) ;
my $movies = $collection->find( ) ; # READ
while ( my $movie = $movies->next ) { # would prefer for ( @$movies ) {} but oh well
my $title = $movie->{ title } ? $movie->{ title } : 'none' ;
my $releaseYear = $movie->{ releaseYear } ? $movie->{ releaseYear } : 'none' ;
my $count = $movie->{ count } ? $movie->{ count } : 0 ;
say qq{$title ($releaseYear) - $count } ;
my $id = $movie->{ _id } ; # every mongodb record gets an _id
$collection->remove( { _id => $id } ) if $title eq 'none' ; # DELETE
$collection->update(
{ title => $title },
{ '$set' => { count => 1 + $count } }
) ; # UPDATE
}
#LADIES AND GENTLEMEN, WE HAVE CRUD!!!
}
exit ;
{
my $client = MongoDB::MongoClient->new( host => 'localhost', port => 27017 ) ;
my $database = $client->get_database( 'test' ) ;
my $collection = $database->get_collection( 'movies' ) ;
my $data = $collection->find( ) ;
for my $movie ( @movies ) {
say qq{$movie->{ title } ($movie->{ releaseYear })} ;
$collection->insert( $movie ) ; # CREATE
}
}
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