Skip to content

Instantly share code, notes, and snippets.

@stennie
Created August 2, 2012 13:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stennie/3237129 to your computer and use it in GitHub Desktop.
Save stennie/3237129 to your computer and use it in GitHub Desktop.
Example of using $slice and fields() in the MongoDB Perl driver 0.45
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper qw/Dumper/;
use MongoDB;
use MongoDB::OID;
my $connection = MongoDB::Connection->new;
my $db = $connection->mydb;
my $address = '22 Acacia Avenue';
my $doc = {
'address' => $address,
'residents' => [
{ 'unit' => '101', 'firstname' => 'Jenn', 'lastname' => 'Errick', },
{ 'unit' => '102', 'firstname' => 'Bill', 'lastname' => 'Payer', },
{ 'unit' => '103', 'firstname' => 'Bobby', 'lastname' => 'Tables', },
{ 'unit' => '104', 'firstname' => 'Ann', 'lastname' => 'Eggsample', },
{ 'unit' => '105', 'firstname' => 'Thera', 'lastname' => 'Minn', },
],
};
$db->tenants->insert($doc);
# Find the fifth resident at the given $address
# .. using a $slice to skip the first 4 residents and limit 1
my $fifth = $db->tenants
->find({'address' => $address})
->fields({ '_id' => 0, 'address' => 0, 'residents' => {'$slice' => [4,1] } })
->next;
print Dumper(\$fifth);
@fajarhide
Copy link

hi stennie,
how to make a key value at $doc into the function "while"? I have such data in the form of an array to be processed automatically in mongodb? may you give me a few examples :) thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment