Mongo CRUD
MongoDB has an appeal to me given its apparent flexibility. I certainly haven’t gotten to the center yet to tell you if the candy deep down under the wrapper is sweet, but my initial impression is that MongoDB is dang near as fun as shopping.
With that non-sense out of the way let’s take a casual tour of MongoDB using the Perl driver MongoDB to express basic CRUD.
Context
Let’s consider CRUD on web documents. We want to create, read, update and delete them. Further let’s assume we’ve got a MongoDB::Collection referred to by $self->collection (maybe your CRUD class consumes a DB Role which provides this for you, hint). Let’s run through the CRUD methods.
Create
Create a page in the database. In this example, we add a $page_struct (think some random HashRef) to the collection using insert. In addition, we’ve include the time() as part of the HashRef under the ‘created’ key. We return the id string which is the value attribute of a MongoDB::OID object. This may be handy later.
sub create { my ( $self, $page_struct ) = @_; # add save time as last_modified and created $page_struct->{last_modified} = $page_struct->{created} = time(); #say "creating page at: ", time(); my $id = $self->collection->insert($page_struct); return $id->value; }
Read
Read a page from the database. This is straightforward, give an id to the find_one() method1 and get back a document.
sub read { my ( $self, $id ) = @_; my $oid = MongoDB::OID->new( value => $id ); return $self->collection->find_one( { _id => $oid } ); }
Update
Update a page in the database. Here we input a $page_struct (the Hashy thing) and an id which are passed along to the update() function.
sub update { my ( $self, $id, $page_struct ) = @_; my $oid = MongoDB::OID->new( value => $id ); $page_struct->{last_modified} = time(); #say "CRUD updating page at: ", time(); $self->collection->update( { '_id' => $oid }, $page_struct ); }
Delete
Delete a page from the database. Give an id, lose a document.
sub delete { my ( $self, $id ) = @_; my $oid = MongoDB::OID->new( value => $id ); $self->collection->remove( { '_id' => $oid } ); }
Footnotes
1 find_one() is the Perl equivalent of findOne() which the mongo db client uses because of its JavaScript nature.
Showing changes from previous revision. Removed | Added
