Limit, Skip & Sort In MongoDB: 4 Things You (2 Min) Need To Know

preview_player
Показать описание
In this tutorial, you'll learn how to use the limit, skip and sort methods in the MongoDB database.



Video Transcript:

Hi guys, this is Abhi from Gokcedb. In this video, you're going to learn four ways to use the limit skip and sort methods in the MongoDB database. Number one, to select all the documents in a collection you can use the find method with empty parentheses.

To limit the number of records in the results set you can use the limit method. Passing 0 to the limit method won't limit any number of records however if I pass 2 then the result set will be limited to 2 documents. Number two, use the skip method to skip the given number of documents in the result set.

On line 7, I'm limiting the result set to two documents but skipping the first one. On line 8, I'm limiting the result set to two documents and skipping the first four documents. This will result in only one document being returned because right now the collection only has five documents.

Number three, use the sort method to sort the result set in ascending or descending order. On line 11, I'm first using the limit method to limit the number of records to 4 then I'm slipping the first document and finally I'm using the sort method to sort the result set by APN in ascending order. Last but not the least, number four.

You can use projection in conjunction with limit skip and sort methods to restrict the output to certain fields. On line 14, I'm first using the find method to restrict the output to APN and County fields then limiting the number of documents to 4 skipping 1, and finally sorting by APN in descending order. There you have it.

Make sure you like, subscribe, and turn on the notification bell. Until next



// 1. Use limit() method to specify the maximum number of documents returned
//
// 2. Use skip() method with limit() to skip number of documents

// 3. Use sort() method with limit() & skip() to sort in ascending order

// 4. Use projection with limit, skip and sort methods to restrict fields and sort in descending order
Рекомендации по теме