Mongo sort Query based on multiple field

Sort Query based on multiple fields in Mongo.

Example:

[
{
"_id" : ObjectId("60179dd62381fc69d5f1c5a0"),
"Emp_Name" : "Jatin",
"Emp_Age" : NumberInt(24),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "B",
"Emp_Joining_Date" : ISODate("2020-07-03T18:30:00.000+0000")
}
{
"_id" : ObjectId("60179dd62381fc69d5f1c5a1"),
"Emp_Name" : "Terens",
"Emp_Age" : NumberInt(27),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "B",
"Emp_Joining_Date" : ISODate("2019-04-03T18:30:00.000+0000")
}
{
"_id" : ObjectId("60179dd62381fc69d5f1c5a2"),
"Emp_Name" : "Manu",
"Emp_Age" : NumberInt(21),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "A",
"Emp_Joining_Date" : ISODate("2020-07-03T18:30:00.000+0000")
}
{
"_id" : ObjectId("60179dd62381fc69d5f1c5a3"),
"Emp_Name" : "Sagun",
"Emp_Age" : NumberInt(20),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "A",
"Emp_Joining_Date" : ISODate("2019-01-03T18:30:00.000+0000")
}
{
"_id" : ObjectId("60179dd62381fc69d5f1c5a4"),
"Emp_Name" : "Pankaj",
"Emp_Age" : NumberInt(60),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "B",
"Emp_Joining_Date" : ISODate("2019-02-03T18:30:00.000+0000")
}
]

Approach

Query: Sort the document based on Emp_Grade and  Emp_Age. 

Sorting will be done first based on the first field and then it will again sort based on another field, the mandatory thing is that the first field should be common (unique).

 
 db.Employee_Detail.aggregate({$sort:{"Emp_Grade":1,"Emp_Age":1}})


Output: 

[
{
"_id" : ObjectId("60179dd62381fc69d5f1c5a3"),
"Emp_Name" : "Sagun",
"Emp_Age" : NumberInt(20),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "A",
"Emp_Joining_Date" : ISODate("2019-01-03T18:30:00.000+0000")
}

{
"_id" : ObjectId("60179dd62381fc69d5f1c5a2"),
"Emp_Name" : "Manu",
"Emp_Age" : NumberInt(21),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "A",
"Emp_Joining_Date" : ISODate("2020-07-03T18:30:00.000+0000")
}

{
"_id" : ObjectId("60179dd62381fc69d5f1c5a0"),
"Emp_Name" : "Jatin",
"Emp_Age" : NumberInt(24),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "B",
"Emp_Joining_Date" : ISODate("2020-07-03T18:30:00.000+0000")
}

{
"_id" : ObjectId("60179dd62381fc69d5f1c5a1"),
"Emp_Name" : "Terens",
"Emp_Age" : NumberInt(27),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "B",
"Emp_Joining_Date" : ISODate("2019-04-03T18:30:00.000+0000")
}
{
"_id" : ObjectId("60179dd62381fc69d5f1c5a4"),
"Emp_Name" : "Pankaj",
"Emp_Age" : NumberInt(60),
"Emp_Salary" : NumberInt(34000),
"Emp_Grade" : "B",
"Emp_Joining_Date" : ISODate("2019-02-03T18:30:00.000+0000")
}
]


No comments:

Post a Comment