MongoDB perl 驱动程序:聚合后的结果不同

MongoDB perl driver : different result after aggregation

我有 collection 'books':

{
"_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驱动,结果一样

{'$sort' => {av => -1, scr => -1, time => -1}},

This is likely to be the issue if you're on a recent perl that randomizes hash order. The sort clause needs to be an ordered document. See https://metacpan.org/pod/Mango::BSON#bson_doc for how to do that.

(c) 来自 https://github.com/dagolden