Created
August 2, 2012 13:31
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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