← Back to MongoDB Course | Chapter 3: CRUD — Read | Lesson 5 of 7

limit और skip

limit कितने documents return हों यह cap करता है और skip पहले वालों पर jump करता है, जो साथ में pagination देते हैं।

In this page:

  1. limit/skip
Syntax
javascript
db.collection_name.find(filter).skip(n).limit(n)

limit/skip

cursor.limit(n) ज़्यादा से ज़्यादा n documents return करता है और cursor.skip(n) पहले n को omit करता है। stable pages के लिए इन्हें sort के साथ combine करें। बड़े skips slow हैं क्योंकि MongoDB अभी भी skipped documents walk करता है; एक indexed field पर range queries बेहतर scale करती हैं।

Note: paging से पहले हमेशा sort करें ताकि pages consistent रहें।

उदाहरण: limit/skip

bash
test> db.items.insertMany([1, 2, 3, 4, 5, 6, 7].map((n) => ({ _id: n, label: "item" + n })))
{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6, '6': 7 }
}
test> db.items.find().sort({ _id: 1 }).limit(3)
[
  { _id: 1, label: 'item1' },
  { _id: 2, label: 'item2' },
  { _id: 3, label: 'item3' }
]
test> db.items.find().sort({ _id: 1 }).skip(3).limit(3)
[
  { _id: 4, label: 'item4' },
  { _id: 5, label: 'item5' },
  { _id: 6, label: 'item6' }
]
test> db.items.find().sort({ _id: -1 }).limit(2)
[ { _id: 7, label: 'item7' }, { _id: 6, label: 'item6' } ]

⚠️ 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 के paging करना
  2. huge skip values इस्तेमाल करना
  3. यह भूल जाना कि limit sort के बाद apply होता है
चैप्टर सारांश
  • limit result size cap करता है
  • skip leading documents omit करता है
  • Stable pages के लिए पहले sort करें
  • बड़ी collections के लिए range paging prefer करें
🔒

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.