How can I sort by multiple fields in mongodb with Perl?

心已入冬 提交于 2019-12-10 19:09:21

问题


How can I get multiple sort in MongoDB with Perl?

My current approach looks something like this:

my $sort = {"is_instock" => -1, "ua" => 1};
my $resultSet = $collection
   ->find({moderated => 1, markers => {'$all'=>$obj->{markers}}})
   ->sort($sort)
   ->limit(25);
@{$result} = $resultSet->all;

But, i got array sorted by one field(ua). What i did wrong?


回答1:


The basic problem here is that a "hash" in Perl is ordered by "key" by default. In order to get the "order of insertion" you need to use Tie::IxHash as follows:

use Tie::IxHash;

my %sort;
tie ( %sort, 'Tie::IxHash' );

my $sort = \%sort;
$sort  =  { "is_instock" => -1, "ua" => 1 };

Then when you use this in your MongoDB query, the keys are considered in the order you inserted them, rather than their lexcial order.

It should have been orderd that way anyhow since the keys are in lexical order, but I suggest you did something wrong and you need to be aware of the insertion order anyway.

The otherwise reason is that "in_stock" does not exist, or is not the true path name to the field. You need to specifiy the full path to the field with "dot notation" otherwise the path is invalid.



来源:https://stackoverflow.com/questions/32967038/how-can-i-sort-by-multiple-fields-in-mongodb-with-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!