
Question:
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?
Answer1: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 <a href="https://metacpan.org/pod/Tie::IxHash" rel="nofollow">Tie::IxHash
</a> 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 <a href="http://docs.mongodb.org/manual/core/document/#dot-notation" rel="nofollow">"dot notation"</a> otherwise the path is invalid.