sort() का उपयोग
sort results को 1 से ascending या -1 से descending order करता है, और कई fields इस्तेमाल कर सकता है।
In this page:
Syntax
db.collection_name.find(filter).sort({ field: 1 })
db.collection_name.find(filter).sort({ field1: -1, field2: 1 })
sort()
cursor.sort({ field: 1 }) ascending sort करता है और -1 descending। ties break करने के लिए order में कई fields list करें। बड़े data पर बिना index के sort करना slow हो सकता है या memory limit hit कर सकता है, इसलिए जो sort fields आप अक्सर query करते हैं उन्हें index करें।
Note:
Sort keys का order matter करता है: { a: 1, b: -1 } पहले a से फिर b से sort करता है।
उदाहरण: sort()
test> db.players.insertMany([
... { _id: 1, name: "Ada", team: "red", score: 30 }, { _id: 2, name: "Bob", team: "blue", score: 50 },
... { _id: 3, name: "Cy", team: "red", score: 50 }, { _id: 4, name: "Di", team: "blue", score: 10 }
... ])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.players.find({}, { _id: 0 }).sort({ score: -1, name: 1 })
[
{ name: 'Bob', team: 'blue', score: 50 },
{ name: 'Cy', team: 'red', score: 50 },
{ name: 'Ada', team: 'red', score: 30 },
{ name: 'Di', team: 'blue', score: 10 }
]
test> db.players.find({}, { name: 1, _id: 0 }).sort({ score: -1 }).limit(2)
[ { name: 'Bob' }, { name: 'Cy' } ]
⚠️ 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. #}
आम गलतियां
- asc या desc strings इस्तेमाल करना
- top-N के लिए limit के साथ sort भूल जाना
- बिना index के बड़ी collections sort करना
चैप्टर सारांश
- 1 ascending के लिए, -1 descending के लिए है
- कई keys ties break करती हैं
- Sort fields index करें
- top-N के लिए limit के साथ combine करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: