Video Transcript (English)
Welcome! In this video, we’ll learn to return query results in a specified order and to constrain the number of results returned.
To do this, we’ll use two cursor methods, `cursor.sort()` and `cursor.limit()`.
First, some context on cursors and cursor methods in MongoDB.
A cursor is a pointer to the result set of a query.
The `db.collection.find()` method returns a cursor that points to the documents that match the query.
Cursor methods, which are chained to queries, can be used to perform actions on the result set - like in this case sorting and limiting the number of results - before returning the desired data or information to the client.
Ok, let’s see the sort() and limit() cursor methods in action.
First, we’ll return results in a specified order using the `sort()` method.
We’re working with a database called `training` and querying its `companies` collection.
We run a `findOne()` query to see a sample document and the fields used in this collection.
This document contains a variety of data about a company.
Say we want to return the data on all music companies, sorted alphabetically from A to Z.
We start by writing a query to return all documents with the category code `music`.
To sort the results, we chain the `sort()` method to the query.
`sort()` takes a document that contains one or more field-value pairs. These specify the fields to sort by and the direction of the sort: 1 for ascending, -1 for descending.
Since we want to sort the company names from A to Z, which is in ascending order, we set the `name` field to 1.
And we see the results sorted.
We’ve seen how to sort query results using an example sorted on a string field.
We can sort numeric fields or fields of any other type in the same way.
Now let’s limit the number of results returned.
Limiting the number of results can enhance performance of an app by avoiding unnecessary data processing.
We use the limit() cursor method to do this.
Say we want to find the three music companies with the highest number of employees.
First we write a query to select music companies.
We sort by number of employees in descending order, since we want the highest numbers returned first.
Finally, we add the limit() method, and specify three as the maximum number of documents to return.
We run the operation and return the top three matching results.
To summarize, in this video we learned to sort and limit query results.
Use `cursor.sort()` to return query results in a specified order.
This method takes a sort object.
Use `cursor.limit()` method to constrain the number of results returned.
This method takes a maximum number of results to return.
Limiting the number of results can improve the performance of your app by avoiding unnecessary data processing.