Mongo:分组,推送和排序

时间:2015-02-03 14:48:35

标签: node.js mongodb aggregation-framework

我有一个mongodb收集数据,如下所示;我想按EmployeedID分组(即0001),然后排序(按年龄)

{
"_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
 }

我知道我可以使用以下方式进行分组。

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

但是我怎么能在这里使用$ sort?所以我的结果可能如下所示;

[{ "EmployeeID" : "0001",
"speciality" : [ "zzz","xxx"],
 "Code" :[ "P","P"],
 "Age" : [5,8]
 }]

2 个答案:

答案 0 :(得分:2)

您可以在分组阶段之前对文档进行排序:

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

答案 1 :(得分:1)

在处理大型集合时,在分组之前进行排序可能会超出mongo的记忆。幸运的是,您可以将allowDiskUse设置为true以允许mongo写入临时文件。