$sort in the cursor -priority of the subsequent fields of sorting

In the $sort operator of aggregation, if I specify multiple values based on which to sort, then the subsequent values seem to have no effect in case of a conflicting value. Please refer the screenshot below.

image

The second field used to sort is hasMagneticField which has a boolean value, so true scores over false. That means Earth should have shown above Mars but since the numberOfMoons value of Mars is more, it comes up. So if a planet with lesser number of moons were to have a value true in the hasMagneticField field, it will still show lower in result set. Seemingly, the second field will have no effect in the sort order.

Is this correct, or there’s some other way for sort to work.

Thanks.

@Apurva_Kunkulol,

Be specified with order in sort as in your project stage:

db.solarSystem.aggregate([{$project: { _id:0, name:1, hasMagneticField:1, numberOfMoons:1}}, {$sort: {hasMagneticField: -1, numberOfMoons: -1 }}])

@Apurva_Kunkulol,
Your condition also is true, you have gave first sort by numberOfMoons fields - and that’s what mongodb does (you see the result first sorted with number of moons field). Please go through the video again to understand.

1 Like

Thanks for your comment Suresh. I think you should refer to my question again.
What I am asking is if the later values in the $sort stage, will have any effect on the end result.
because seemingly it doesn’t.
The point you’ve raised is also new. I mean the sort order has to be same as the project order for the sort to work, is it?
In the video, (probably, I didn’t come across) it doesn’t say if the sort order has to be identical to the project order.
So my question still is.

Thanks.

@ Apurva_Kunkulol

Looking at your screen shot (with some difficultly as it’s white text on a black background) it looks correct to me and your question seems incorrect. The sort is first of all by numberOfMoons, then by hasMagneticField. So, following normal sort logic, the hasMagneticField only is used as a tie-breaker when there is more than one document with the same numberOfMoons. In this set, only the documents with numberOfMoons = 0 fit that criteria, and they are obviously sorted correctly.

And where did you get the idea that the sort order must match the projection???

@DHz
Thanks for this explanation. It makes the working a lot clearer.

@Suresh_58788 made that comment earlier, so I thought maybe I don’t have the full idea of the working of $sort, hence the question.