$setWindowFields is slow to $rank

I have a relatively large dataset that i need to rank, dividing by multiple partisions using $setWindowFields. Approximately 155k documents to rank.

Is there any way to speed this part of my aggregation up. If i run an explain on the aggregation, the sorting part of the $setWindowFields is what is taking the longest - upto 6 seconds.

Any ideas?

{
    partitionBy : {
        age : '$age',
        gender : '$gender.id',
    },
    sortBy : {
        dob: 1,
    },
    output : {
        rank: {
            $rank : {
            }
        },
    }
}

You can add a $sort stage before $setWindowFields to sort the data by the dob field. This will improve performance by ensuring that the data is already in the desired order before ranking.

Thanks for the comment. It appears i gain nothing from adding a sort prior to the $setWindowFields.

$setWindowFields already does it’s own sorting, and adding another sort prior to, ads another 2.4 seconds onto the query.