MongoDB Sort document-Programmershelper

0
243
Spread the love

Introduction

In this article, we learn MongoDB sort document.My main focus describes its simple steps. The word sort means sorting something.Sorting is always done in ascending or descending order.In MongoDB Sorting performs using 1 and -1.For ascending order 1 is used while descending order -1 is used.

Prerequisite

You should also read my previous articles.In which I explained and MongoDB Remove document step by step guideline

Implementation Section

  • Ascending order
  • Descending order

In Sort() method always write the sorting order as a parameter. the following is the basic syntax.

  • <db> is a reserved word.
  • <Collection_name> writes the collection name.
  • <Sort> is also reserved word used for sorting in ascending and descending
  • Inside the bracket write the document <specific_criteria for sorting data>.

Practical work

Ascending order

Here  I am fetched a record from a database.whose order is ascending.The below code add into the database then fetch it ascending order.If we do not write sorting order then this method is equivalent to Find() method.

The following example will display the documents sorted by <Age>in the ascending order.show in below fig.

output

Alt Tag MongoDB sort documentDescending order

Here  I am fetched a record from a database.whose order is descending.
If we do not write sorting order then this method is equivalent to Find() method.

The following example will display the documents sorted by <Age>in the descending order.show in below fig.

Output

Alt Tag MongoDB sort document

 

Limit with sort()

you can also use sort() method for a limit and access the limit result.here this query gives the limit result.

Conclusion

I wish I could tell you that a great site of MongoDB.you just understands key element above post-MongoDB sort document.You also read my previous lecture.I hope you will understand this lecture.Thank you for reading this lecture. Hope you got the idea.