我有收藏'书籍':
{
"_id" : ObjectId("54901b078b823f2014080700"),
"title" : "title1",
"available" : 0,
"time" : 14318789245,
"score" : 1,
"categories" : ["fiction","humor"]
},
{
"_id" : ObjectId("54901b078b823f2014080701"),
"title" : "title2",
"available" : 1,
"time" : 14318789745,
"score" : 1,
"score_fiction": 5,
"categories" : ["fiction",]
}
...
{
"_id" : ObjectId("54901b078b823f2014080751"),
"title" : "titleN",
"available" : 1,
"time" : 14318789545,
"score" : 4,
"score_fiction": 2,
}
我将用这个脚本聚合它:
my $books = $mango->db('test')->collection('books')->aggregate([
{'$match' => {categories => fiction}},
{'$project' =>
{
'av' => {'$cmp' => ['$available', 0] },
title => 1,
scr => {'$ifNull' => ['$score_fiction' , '$score'] },
time =>1}
},
{'$sort' => {av => -1, scr => -1, time => -1}},
{'$limit' => 10}
]);
while (my $book = $books->next) {
print $book->{title} . " [" . $book->{scr} . "]\n";
5-7次运行后,我得到两个不同的结果:
当我在mongo的shell中运行这个聚合管道时 - 它可以正确排序。
db.books.aggregate([{'$match' : {categories : 'fiction'},
{'$project' : {'av' : {'$cmp' : ['$available', 0] },
title : 1,
scr : {'$ifNull' : ['$score_fiction' , '$score'] },
time:1}},
{'$sort' : {av : -1,scr :-1, time : -1}},
{'$limit': 10}]);
问题出现在司机或脑海中?
PS我试过Mango和官方MongoDB驱动程序,但结果是一样的。
答案 0 :(得分:0)
{'$ sort'=> {av => -1,scr => -1,time => -1}},
如果你是最近的perl,这可能是个问题 随机化哈希顺序。 sort子句需要是有序的 文献。有关如何,请参阅https://metacpan.org/pod/Mango::BSON#bson_doc 那样做。