我有一个场景需要在mongoDB中对group()的结果进行排序
例如:
假设您在学生集合中有文档,如下所示
{
"id":"kjdkfdjkljflkd73847",
"DepartementID":123,
"parties":[
{
"idNumber" : "103",
"studentName" : {
"suffix" : "Mr",
"firstName" : "ram",
"middleName" : "",
"lastName" : "gorli"
}
},
{
"idNumber" : "99",
"studentName" : {
"suffix" : "Mr",
"firstName" : "ramesh",
"middleName" : "",
"lastName" : "vogue"
}
},
]
},
{
"id":"kjdkfdjkljflkd73847",
"DepartementID":123,
"parties":[
{
"idNumber" : "101",
"studentName" : {
"suffix" : "Mr",
"firstName" : "Mike",
"middleName" : "",
"lastName" : "john"
}
},
{
"idNumber" : "102",
"studentName" : {
"suffix" : "Mr",
"firstName" : "ram",
"middleName" : " ",
"lastName" : "gorli"
}
},
]
}
我在学生集合中使用DepartmentID对细节进行分组,在group()中我需要使用派对中的姓氏进行排序。我们怎样才能在一个查询中实现这一点呢?
请帮帮我。我非常感谢你的努力。
答案 0 :(得分:0)
这对你有用:
db.getCollection('quotes').aggregate([
{
$unwind:"$parties"
},
{
$sort:{
"parties.studentName.lastName": 1
}
},
{
$group:{
_id:"$DepartementID",
parties:{
$push:"$parties"
}
}
}
])