Skip to content

Instantly share code, notes, and snippets.

@MadMartigan
Created February 6, 2013 17:43
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 MadMartigan/4724311 to your computer and use it in GitHub Desktop.
Save MadMartigan/4724311 to your computer and use it in GitHub Desktop.
The mango driver was just release a few hours ago. I thought I would post a little cheatsheet for anyone interested. You can cut an paste this file into your test app to get some data loaded and see a few ways to access it.
<h2>Mango Cheatsheet</h2>
% my $mango = Mango->new('mongodb://localhost:27017')->db('foo')->collection('foo');
% my @records;
% for my $cntr (1..10) {
%
% my @objects;
% for (1..4) {
% my $object = {
% objName => 'objName' . $cntr . $_,
% objType => 'objType' . $cntr . $_,
% objExp => 'objExp' . $cntr . $_
% };
% push(@objects, $object);
% }
%
% my $record = {
% name => 'name' . $cntr,
% title => 'title' . $cntr,
% objects => \@objects,
% stuff => {
% sub1 => 'stuff' . $cntr,
% sub2 => 'stuff' . $cntr,
% sub3 => 'stuff' . $cntr
% }
%
% };
% push(@records, $record);
% };
% my $exists = $mango->find_one({name => 'name1'});
% if (!$exists) {
% $mango->insert(\@records);
Loaded Sample Data
% } else {
Sample data already loaded
% }
<pre>
% my $cursor = $mango->find();
Number of records = <%= @{$cursor->all} %>
% my $doc = $mango->find_one({name => 'name1'});
name1=<%= $doc->{name}; %>
% $doc = $mango->find_one({'stuff.sub2' => 'stuff2'});
stuff.sub2=<%= $doc->{stuff}->{sub2}; %>
Cycle throug all records in collection foo where field 'name' exists:
% my $records = $mango->find({name => { '$exists' => 1 } } );
% while ( my $row = $records->next ) {
Record:
<%= "$row->{name}, $row->{title}, $row->{stuff}->{sub2}" %>
Objects:
% for my $object (@{$row->{objects}}) {
<%= "$object->{objName}, $object->{objType}, $object->{objExp}" %>
% }
% }
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment