首页 > 解决方案 > Error when trying to use MongoDB's cursor sort in Perl

问题描述

This documentation described how to sort the results once you've obtained a cursor.

However, When I try to compile with my own implementation:

#!/asp_share/linopt/perl-5.8.8/bin/perl

use CGI;
use Fcntl;
use MongoDB;
use JSON;
use Text::CSV;
use strict;
use warnings;

my $q = new CGI;
my $dbhost = $q->param('dbhost') || 'sb2mdb01';
print $q->header('application/json');

# Connect to db and retrieve stats for given db
my $client = MongoDB::Connection->new("host" => $dbhost);
my $tracking_db = $client->get_database("db_size_tracking");
my $db_name = "st_" . ($q->param('db') || "db_size_tracking" );
my $collection = $tracking_db->get_collection($db_name);
my $every = $q->param('every') || 1;  # sample per $every line
my $date = $q->param('date') || `date +%Y%m%d`; # date to start from
chomp($date);
my $year = substr($date,0,4);
my $month = "".substr($date,4,2);
my $day = "".substr($date,6,2);
my $cursor = $collection->find({recorded_at => {'$gte' => DateTime->new( year => $year, month => $month, day => $day)}});
$cursor->sort([recorded_at => 1]);
# Generate and return JSON
my @sizeTimes;
my $count = 0;
while (my $doc = $cursor->next) {
    next if ($count++ % $every != 0);
    my $recorded_at = $doc->{'recorded_at'}->iso8601;
    my $datasize = $doc->{'datasize'};
    my %row;
    $row{'recorded_at'} = $recorded_at;
    $row{'datasize'} = $datasize;
    push @sizeTimes, \%row;
}

print encode_json {sizeTimes => \@sizeTimes};

I get

not a hash reference at /linopt/perl-5.8.8/lib/site_perl/5.8.8/i686-linux/MongoDB/Cursor.pm line 182
        MongoDB::Cursor::sort('MongoDB::Cursor=HASH(0x8e87160)', 'ARRAY(0x8e86614)')

I'm fairly new to perl, so I'm not really sure how to interpret this error message, any help would be really appreciated!

The documents returned are of the form

{recorded_at: recorded_at, datasize: datasize}

Perl: v5.8.8 MongoDB: 3.0.7

标签: mongodbperl

解决方案


$cursor->sort({recorded_at => 1});

也可用于按多个字段排序。

该文档适用于 perl 的较新的 MongoDB 驱动程序,我敢打赌,如果您也在查找它,那么您会被卡住。


推荐阅读