Skip to content

Sort and Limit

Estimated time to read: 2 minutes

sort() and limit() can be used to return specific results based on order and quantity of a MQL query.

They are both cursor methods in addition to pretty() and count().

Note

A cursor method is not applied to the data that is stored in a database. It is instead applied to the result set of the cursor.

flowchart LR
    a[Data] --> b(find)
    b(find) --> c[Cursor]

Sort()

sort() method can be used to find a specific document with a certain query.

Lowest value sort()

The example below shows the document being returned with the lowest population value in the sample_training.zips namespace.

db.zips.find().sort({ "pop": 1 }).limit(1)

This query gets all documents, sorts them by their population count in increasing order and then returns the first document in the cursor, in this instance the one with the smallest value.

Note

Though this will return the document with the lowest value in the collection, there may be other documents that share the same value!

db.zips.find({ "pop": 0 }).count() shows that there are 67 documents with a population equal to 0.

Highest value sort()

The sort() method can also be used to find the document with the highest value of a query. This can be done by reversing the sort order.

db.zips.find().sort({ "pop": -1 }).limit(1)

Mixed value sort()

Data can be sorted in one or more fields in increasing or decreasing direction.

db.zips.find().sort({ "pop": 1, "city": -1 })

The result of the command above are sorted by increasing order of population and decreasing order of the city name,

sort().limit()

The .limit() method can be used to return a specified number of documents from the sort() method.

For example, .limit(1) will return a single document, where as .limit(10) will return 10 documents from the sorted collection.

Note

Limit can be used without sort, however, it will not guarantee the order of the returned documents.

Note

Regardless of the order of the sort and limit methods. MongoDB will always assume that the sort method is to be acted upon first.

Lab

db.companies.find(
                { "founded_year": { "$ne": null }},
                { "name": 1, "founded_year": 1 }
                )
            .sort(
                { "founded_year": 1 }
                )
            .limit(5)

We first must filter out the documents where the founded year is not null, then project the fields that we are looking for, which is name, and founded_year in this case. Then we sort the cursor in increasing order, so the first results will have the smallest value for the founded_year field. Finally, we limit the results to our top 5 documents in the cursor, thus getting the 5 oldest companies in this collection.