如何使用Perl在mongodb中按多个字段排序? [英] How can I sort by multiple fields in mongodb with Perl?

查看:113
本文介绍了如何使用Perl在mongodb中按多个字段排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Perl在MongoDB中获得多种排序?

How can I get multiple sort in MongoDB with Perl?

我当前的方法如下:

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

但是,我得到了按一个字段(ua)排序的数组.我做错了什么?

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

推荐答案

此处的基本问题是,默认情况下,Perl中的哈希"由键"排序.为了获得插入顺序",您需要使用 Tie::IxHash 如下:

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 };

然后,当您在MongoDB查询中使用此键时,将按插入键的顺序而不是按词法顺序来考虑键.

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.

否则,原因是"in_stock"不存在,或者不是该字段的真实路径名.您需要使用点符号" 否则,路径无效.

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.

这篇关于如何使用Perl在mongodb中按多个字段排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆