Sorting Documents using sort() method
Using sort() method, you can sort the documents in ascending or descending order based on a particular field of document.
Syntax of sort() method:
db.collecttion_name.find().sort({field_key:1 or -1})
1 is for ascending order and -1 is for descending order. The default value is 1.
For example: collection
For example: collection
studentdata
contains following documents:> db.studentdata.find().pretty()
{
"_id" : ObjectId("59bf63380be1d7770c3982af"),
"student_name" : "Steve",
"student_id" : 2002,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63500be1d7770c3982b0"),
"student_name" : "Carol",
"student_id" : 2003,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63650be1d7770c3982b1"),
"student_name" : "Tim",
"student_id" : 2004,
"student_age" : 23
}
Lets say I want to display the
student_id
of all the documents in descending order:To display only a particular field of document, I am using MongoDB Projection
> db.studentdata.find({}, {"student_id": 1, _id:0}).sort({"student_id": -1})
{ "student_id" : 2004 }
{ "student_id" : 2003 }
{ "student_id" : 2002 }
To display the student_id field of all the students in ascending order:
> db.studentdata.find({}, {"student_id": 1, _id:0}).sort({"student_id": 1})
{ "student_id" : 2002 }
{ "student_id" : 2003 }
{ "student_id" : 2004 }
Default: The default is ascending order so If I don’t provide any value in the sort() method then it will sort the records in ascending order as shown below:
> db.studentdata.find({}, {"student_id": 1, _id:0}).sort({})
{ "student_id" : 2002 }
{ "student_id" : 2003 }
{ "student_id" : 2004 }
You can also sort the documents based on the field that you don’t want to display: For example, you can sort the documents based on student_id and display the student_age and student_name fields.
0 comments:
Post a Comment