Sorting is a very much required database operation. It helps to simplify readability and also the information provided in a great way . Through, this post, you’ll study sorting concept and the way it gets implement within the MongoDB database. So, lets see how to do Sorting in MongoDB.

Sorting is a way of ordering either in increasing order or decreasing order of the measuring quantity. It is use on entities like information (which includes names and facts), numbers also as records. It thus, increases the reading ability and consistency of the displayed data.

Techniques of Sorting in MongoDB

For sorting your MongoDB documents, you would like to form use of the sort() method. This method will accept a document that features a list of fields and therefore the order for sorting. Also, for indicating the sorting order, you’ve got to line the worth 1 or -1 with the precise entity. 1 is use for increasing(ascending) order and -1 is use for decreasing(descending) order.

The sort() method

Syntax :

db.collection_name.find().sort({FieldName1: sort order 1 or -1, FieldName2: sort order})

Consider a set that’s having the subsequent data:

{ "_id" : ObjectId(5983548781331abf45ec5), "topic":"Cyber Security"}
{ "_id" : ObjectId(5565548781331aef45ec6), " topic ":"Digital Privacy"}
{ "_id" : ObjectId(5983549391331abf45ec7), " topic ":"Application Security Engineering"}

To sort in ascending order, we use :

db.techSubjects.find({}, {"topic":1, _id:0}).sort({"topic":1})

MongoDB projection is utilize to display only selected fields of the document.

The above statement will result in:

It is to note, that just in case you are doing not state or explicitly define the sorting preference (1 or -1). Then, the sort() method will exhibit your documents in ascending order by default.

To display the subject field of all the techSubjects in descending order:

You can also specify the sorting of parameters through a replacement field name for the calculated metadata. Which you’ll specify under the $meta expression as a worth.

Here may be a sample document that specifies a descending sort using the metadata “textCount”:

{ count: { $meta: "textCount" } }

Here this specified metadata will determine the type order.

Syntax :

db.collection_name.find(
,
{ value: { $meta: } }
)

#Output :
db.techWriter.find({},
{ count: { $meta: "textCount" } }
).sort( { count: { $meta: "textCount" } } )

Miscellaneous Example

db.collecttion_name.find().sort({field_key:1 or -1})

Lets take for example the collection employeedata contains following documents:

db.employeedata.find().pretty()
{
"_id" : ObjectId("59bf63380be1d7770c3982af"),
"employee_name" : "Shubham",
"employee_id" : 001,
"employeet_age" : 25
}
{
"_id" : ObjectId("59bf63500be1d7770c3982b0"),
"employee_name" : "Raghu",
"employee_id" : 002,
"employeet_age" : 23
}
{
"_id" : ObjectId("59bf63650be1d7770c3982b1"),
"employee_name" : "Ayush",
"employee_id" : 003,
"employeet_age" : 21
}

Lets say I would like to display the student_id of all the documents in descending order:

To display only a specific field of document, i’m using MongoDB Projection

db.employeedata.find({}, {"student_id": 1, _id:0}).sort({"student_id": -1})
{ "employee_id" : 003 }
{ "employee_id" : 001  }
{ "employee_id" : 002 }

# To display the student_id field of all the scholars in ascending order:
db.employeedata.find({}, {"student_id": 1, _id:0}).sort({"student_id": 1})
{ "employee_id" : 001 }
{ "employee_id" : 002 }
{ "employee_id" : 003 }

The default is ascending order so if no value is given the records get sort in ascending order as shown:

db.studentdata.find({}, {"student_id": 1, _id:0}).sort({})
{ "employee_id" : 001 }
{ "employee_id" : 002 }
{ "employee_id" : 003 }

Here’s an article on creating a database in MongoDB

Using the limit() method

The sort() method are often use along side the limit() method that limits search query thus. We need to pass a limit value to set it.

The example given below, uses the “vehicles” collection and the result’s limited to 2 documents. The result is sorted in both the ascending and descending order.

db.vehicles.find({},{_id:0}).sort({"make":1,"year":1}).limit(2).pretty()

For the descending order :

db.vehicles.find({},{_id:0}).sort({"make":-1,"year":-1}).limit(2).pretty()
Sorting in MongoDB

The skip() method

For your information, the skip() method can be conjointly use with the sort() method for doing the various sorting functions. This skip() method allows one person to skip any specified numbers of documents, in the resultant.

db.vehicleinformation.find({},{_id:0}).sort({"year":1}).skip(4).pretty()

CONCLUSION

We have in this article, as promised come up with something, building up on the last article. The one on creating database in MongoDB. In this article, we have seen how to do sorting in MongoDB. For this, we have used various methods like the sort() method, the limit() method and the skip() methods. We have seen all this using various examples and in-depth analysis. Hope to have cleared your doubts in the most suitable way. If you have any queries you can drop them in the comments section.