Chapter 5 Quiz 2: sort() and limit() alternative solution

Another solution which uses $group and 1. does not require to know that there should be some empty values and 2. gives a more detailed view of the data – which I like. :slight_smile:

        {_id: "$birth year", count: {$sum: 1}}
    {$sort: {"_id": -1}}

Yes. But at a much higher processing cost. In particular if there is an index. Your solution will have to perform a collection scan and process all documents of the collection. A find/sort/limit would do an index scan and output only one document and right away when the document is found.

Yes. But you are counting them and the result is part of your output. Having a

is interesting when it is related to your use-case.

So your solution works but is not optimal to answer the question.

1 Like

Indeed. I was not aware of processing cost, you are right. I just think that it is worth to develop different solutions to a problem while learning and this was also a good opportunity for me to understand how $group works deeper. And maybe for others, that’s why are posted it. :slight_smile:

Thank you for this explanation. Very useful, develops my thinking. :slight_smile:

Of course. I consider this an advantage: I do not have to know anything about the data in advance, the query itself shows me the properties of the data instead.

:+1: Thanks for your comment! That’s a great forum!


I totally agree.

Studying alternatives and starting a discussion about them is a good way to increase our knowledge.

I’m all in.

1 Like

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