Reputation: 2871
I have the following aggregate query to sort grouped data and return it in pages:
Product.aggregate([
{ $match : { categories : category, brand : { $ne: null } }},
{ $group : { _id : '$brand', rating: { $max: '$rating' } } },
{ $sort : { rating : -1 } },
{ $skip : skip },
{ $limit : limit }], function(error, results){
....
})
This is meant to find the brands of the products with the input category and with a brand, group them by brand, and sort the brand groups by the highest rated product in the brand group. This is then meant to be paginated, using skip and limit parameters.
When I paginate it I end up getting occasional results repeating (just one group every now and then, I haven't noticed a pattern). I know that the data does not include repeated products, and none of the data is changing between calls, so what am I doing wrong with the query to get these results?
Upvotes: 2
Views: 827
Reputation: 4117
The issue in the aggregation is linked to the case when there are several brands with the same rating. In that case, you cannot guarantee that those will appear in the same order.
The solution is to force a brand sort for the equal rating cases:
{ $sort : { rating : -1, "_id" : 1 } }
Upvotes: 5