If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
किसी collection से documents को fetch करते समय आपने देखा ही होगा कि by default documents को order वही होता जिस order में आपने insert किये थे। और कई जगह ऐसे need आती है कि हमें किसी particular field के according records को fetch करना होता है।
और इस topic में हम documents को order के according fetch करना सीखेंगे।
●●●
MongoDB में sorting के लिए sort()
method का use किया जाता है। यह एक तरह से SQL ORDER BY की तरह work करता है।
sort()
method MongoDB में data को sort करने के लिए use किया जाता है। इस method से आप MongoDB collection में stored documents को specified field के according ascending (A to Z
) ya descending (Z to A
) order में sort कर सकते हैं।
db.collectionName.find().sort({ fieldname: 1 }) // Ascending order db.collectionName.find().sort({ fieldname: -1 }) // Descending order
Syntax में collectionName
एक collection का नाम है और fieldname
आपके documents में sort करने करने के लिए use किया गया field का नाम है। 1 ascending order को represent करता है और -1 descending order को।
●●●
Suppose आपके पास एक "employees"
collection है जिसमे employees की details stored है ।
अब अगर आपको documents को age
के bases पर descending order (घटते क्रम) में sort करना है तो कुछ इस तरह से करेंगे -
db.employees.find().sort({ "age" : -1 })
ऊपर दी गयी MongoDB query की SQL equivalent query कुछ इस तरह से होगी -
SELECT * FROM employees
ORDER BY age DESC;
हालाँकि आप चाहे तो find() Method में need के according कोई condition भी pass कर सकते हैं।
जैसे नीचे दिए गए example में salary को ascending order में active employee fetch किये गए है।
db.employees.find({"status" : "active"}).sort({ "salary" : 1 })
SQL equivalent query
SELECT * FROM employees
WHERE status="active"
ORDER BY salary ASC;
इसी तरह से आप advance conditions भी apply करके documents को fetch कर सकते हैं।
●●●
हालाँकि aggregate() में भी records को fetch करने के लिए $sort stage का use किया जाता है।
Suppose आपको students
collection से create_date
के basis पर descending order में records fetch करने हैं तो query कुछ इस तरह से होगी।
db.students.aggregate([ { $sort : { created_date : -1 } } ]);
Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)
Get connected with me. :) LinkedIn Twitter Instagram Facebook