M001 chapter 5 quiz1 of sort

Hi, lecture 5 says in MongoDB should always use “sort” first then use “limit”, otherwise you might get the wrong answer. How come the last option is indicated as the right answer???

Because sort, skip and limit are reordered to the most logical order, so the order you specify them does not matter.

Starting collection:

c.find()
[
  { _id: 1 },
  { _id: 2 },
  { _id: 3 },
  { _id: 4 },
  { _id: 5 },
  { _id: 6 }
]

and then all combinations of the 3 methods lead to the same result

Atlas rent-shard-0 [primary] test> c.find().sort( { _id : -1 } ).skip( 2 ).limit( 2 )
[ { _id: 4 }, { _id: 3 } ]
Atlas rent-shard-0 [primary] test> c.find().sort( { _id : -1 } ).limit( 2 ).skip( 2 )
[ { _id: 4 }, { _id: 3 } ]
Atlas rent-shard-0 [primary] test> c.find().limit( 2 ).sort( { _id : -1 } ).skip( 2 )
[ { _id: 4 }, { _id: 3 } ]
Atlas rent-shard-0 [primary] test> c.find().skip( 2 ).sort( { _id : -1 } ).limit( 2 )
[ { _id: 4 }, { _id: 3 } ]
Atlas rent-shard-0 [primary] test> c.find().skip( 2 ).limit(2).sort( { _id : -1 } )
[ { _id: 4 }, { _id: 3 } ]
Atlas rent-shard-0 [primary] test> c.find().limit( 2 ).skip(2).sort( { _id : -1 } )
[ { _id: 4 }, { _id: 3 } ]

I tried to find where it is written that this is the way it works but could not.

1 Like

Hi @farideh_gorji,

Quoting what the instructor said in the lecture at 2:50:

The caveat with limit() is that if you use limit() without sort(), 
you will most likely get some results without any guarantee of its order.

Similarly, if you use limit() before you sort(), 
you might miss some of the data that you meant to sort and 
include in the results set.

Which is why MongoDB assumes that when you use sort() 
and limit(), you always mean to sort first, regardless of 
the order in which you type these.


(attaching a screenshot from the lecture video for your reference too :smile:)

The same is illustrated by @steevej’s amazing example and the documentation, mentions the same too, ie. regardless of which goes first in your chain of commands, sort() would be always applied before the limit().

Let us know if the doubt still persists. Feel free to reach out for anything else as well.

Regards,
Satyam

2 Likes

Hi Satyam, Thank you very much for all your efforts trying to explain the subject.
Regards,
Farideh

3 Likes

Hi Steeve ,
Thank you very much for your respond and explanations.
Regards,
Farideh

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.