← Back to MongoDB Course | Chapter 7: Aggregation | Lesson 5 of 7

$sort, $limit और $skip

ये stages एक pipeline से गुज़रते documents को order, trim, और page करती हैं।

In this page:

  1. $sort/$limit/$skip
Syntax
javascript
{ $sort: { field: -1 } }
{ $skip: n }
{ $limit: n }

$sort/$limit/$skip

$sort documents order करता है, $limit पहले n रखता है, और $skip पहले n drop करता है। Sort फिर limit top-N results देता है और MongoDB उस combination को optimize कर सकता है।

Meaningful paging के लिए $sort को $limit और $skip से पहले रखें, और बड़े data के लिए एक supporting index सुनिश्चित करें।

Note: $sort के बाद $limit एक top-N sort में optimize हो जाता है।

उदाहरण: $sort/$limit/$skip

bash
test> db.scores.insertMany([{ _id: 1, n: "Ada", s: 70 }, { _id: 2, n: "Bob", s: 90 }, { _id: 3, n: "Cy", s: 85 }, { _id: 4, n: "Di", s: 60 }, { _id: 5, n: "Ed", s: 95 }])
{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
}
test> db.scores.aggregate([{ $sort: { s: -1 } }, { $limit: 3 }, { $project: { _id: 0, n: 1, s: 1 } }])
[ { n: 'Ed', s: 95 }, { n: 'Bob', s: 90 }, { n: 'Cy', s: 85 } ]
test> db.scores.aggregate([{ $sort: { s: -1 } }, { $skip: 2 }, { $limit: 2 }, { $project: { _id: 0, n: 1 } }])
[ { n: 'Cy' }, { n: 'Ada' } ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. $sort से पहले $limit इस्तेमाल करना
  2. बिना एक stable sort के skip करना
  3. बड़ी collections पर बिना index के sort करना
चैप्टर सारांश
  • $sort order करता है
  • $limit n रखता है
  • $skip n drop करता है
  • पहले Sort करें, फिर limit या skip
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.