Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo: Group, push and sort

I have a mongodb collection data as per below;I want to group by EmployeedID( i.e 0001) and then sort(by age)

{
"_id" : ObjectId("54d0512191a4da7736e9db43"),
"EmployeeID" : "0001",
"Speciality" : "xxx",
"Code" : "P",
"Age" : 8
}

/* 1 */
{
"_id" : ObjectId("54d0512191a4da7736e9db44"),
"EmployeeID" : "0002",
"Speciality" : "yyyyy",
"Code" : "P",
"Age" : 6
 }

/* 2 */
{
"_id" : ObjectId("54d0512191a4da7736e9db45"),
"EmployeeID" : "0001",
"Speciality" : "zzz",
 "Code" : "P",
 "Age" : 5
 }

I know I can group using the following way.

collection.aggregate([
{$match:{"EmployeeId":0001}},
{$group:{"_id":"$EmployeeID",
        "speciality":{$push:"$Speciality"},
        "Code":{$push:"$Code"},
        "Age":{$push:"$Age"}}}
 ])

But how can I using $sort here? SO my result can be something like below;

[{ "EmployeeID" : "0001",
"speciality" : [ "zzz","xxx"],
 "Code" :[ "P","P"],
 "Age" : [5,8]
 }]
like image 869
FRizal Avatar asked Jan 09 '23 23:01

FRizal


2 Answers

You can sort the document prior to the grouping stage:

collection.aggregate([
{$sort: {_id: -1}},
{$match:{"EmployeeId":0001}},
{$group:{"_id":"$EmployeeID",
    "speciality":{$push:"$Speciality"},
    "Code":{$push:"$Code"},
    "Age":{$push:"$Age"}}}
])
like image 102
eladcon Avatar answered Jan 17 '23 22:01

eladcon


Sorting prior to grouping may exceed mongo's memory when dealing with large collections. Fortunately, you can set allowDiskUse to true to allow mongo to write temporary files.

like image 23
Ionut Manolache Avatar answered Jan 17 '23 23:01

Ionut Manolache