mongodb - 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
解决方案
$cursor->sort({recorded_at => 1});
也可用于按多个字段排序。
该文档适用于 perl 的较新的 MongoDB 驱动程序,我敢打赌,如果您也在查找它,那么您会被卡住。
推荐阅读
- python - 试图在文件中找到最长的单词 - Python
- python - 无法跳过龙卷风 python 测试类中的某些方法
- r - 多列 t 检验的一个微妙问题
- mysql - 如何在某个级别上获得用户的位置?(mysql)
- javascript - 如何使用 vuejs 获取数据的函数
- cassandra - 遇到“Could not reserved enough space for 2097152KB object heap”
- firebase - Firebase Unity SDK 是否在主线程上吃异常?
- c# - Azure 功能。返回任务
不等待与异步/等待 - python - pandas.to_datetime() 如何从本地时区转换为 UTC unix 时间戳?
- r - 不要在 R 中的自己的包中公开导入包中的函数