Mosius
1 min readApr 22, 2022

--

I know it's pretty late, but I hope it helps you or others who might read this article.

If we see it as a recursion, it becomes easier to interpret & understand; in that manner the base case is to reach an identical field to sort upon(_id in this example).

let’s start with the first condition:

$or: [

{ price: { $gt: 99 } },

]

for the next step, we should assume the price is the same, and think of only 2 fields to sort upon and exactly do as explained in the article:

$or: [

{ price: { $gt: 99 } },

{

price: 99,

$or: [

{ rating: { $gt: 4 } },

{

rating: 4,

_id: { $gt: ObjectId("5f7f1f7d67f67ddaa622b796") },

},

],

},

],

and as the final step, we should assume rate is also the same, and add the base case where we only sort upon the identical field:

$or: [

{ price: { $gt: 99 } },

{

price: 99,

$or: [

{ rating: { $gt: 4 } },

{

rating: 4,

_id: { $gt: ObjectId("5f7f1f7d67f67ddaa622b796") },

},

],

},

{

price: 99,

rating: 4,

_id: { $gt: ObjectId("5f7f1f7d67f67ddaa622b796") },

},

],

It is a bit complex, but its time complexity is still O(1). When there is more than 2 fields to sort upon, and there is not a large amount of data, I encourage you to use the skip-limit method. Also, you need to consider applying proper indexing in both cases (as I mentioned in Worse Performance and Fix section).

--

--

Responses (1)