이를 위해 $sort() 연산자와 함께 집계() 메서드를 사용할 수 있습니다. 개념을 이해하기 위해 문서로 컬렉션을 만들어 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다 -
> db.aggregationSortDemo.insertOne({"StudentId":98,"StudentFirstName":"John","StudentLastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90140c5705caea966c5587")
}
> db.aggregationSortDemo.insertOne({"StudentId":128,"StudentFirstName":"Carol","StudentLastName":"Taylor"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90141b5705caea966c5588")
}
> db.aggregationSortDemo.insertOne({"StudentId":110,"StudentFirstName":"David","StudentLastName":"Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90142f5705caea966c5589")
}
> db.aggregationSortDemo.insertOne({"StudentId":139,"StudentFirstName":"Chris","StudentLastName":"Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90146a5705caea966c558a")
}
> db.aggregationSortDemo.insertOne({"StudentId":125,"StudentFirstName":"Sam","StudentLastName":"Williams"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9015695705caea966c558b")
}
> db.aggregationSortDemo.insertOne({"StudentId":139,"StudentFirstName":"Mike","StudentLastName":"Wilson"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90158e5705caea966c558c")
} find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다 -
> db.aggregationSortDemo.find().pretty();
다음은 출력입니다 -
{
"_id" : ObjectId("5c90140c5705caea966c5587"),
"StudentId" : 98,
"StudentFirstName" : "John",
"StudentLastName" : "Smith"
}
{
"_id" : ObjectId("5c90141b5705caea966c5588"),
"StudentId" : 128,
"StudentFirstName" : "Carol",
"StudentLastName" : "Taylor"
}
{
"_id" : ObjectId("5c90142f5705caea966c5589"),
"StudentId" : 110,
"StudentFirstName" : "David",
"StudentLastName" : "Miller"
}
{
"_id" : ObjectId("5c90146a5705caea966c558a"),
"StudentId" : 139,
"StudentFirstName" : "Chris",
"StudentLastName" : "Brown"
}
{
"_id" : ObjectId("5c9015695705caea966c558b"),
"StudentId" : 125,
"StudentFirstName" : "Sam",
"StudentLastName" : "Williams"
}
{
"_id" : ObjectId("5c90158e5705caea966c558c"),
"StudentId" : 139,
"StudentFirstName" : "Mike",
"StudentLastName" : "Wilson"
} 다음은 MongoDB 집계 정렬에 대한 쿼리입니다.
사례 1 − 결과를 내림차순으로 원할 때마다. 쿼리는 다음과 같습니다 -
> db.aggregationSortDemo.aggregate( {$group: {_id: '$StudentId',"TotalOccurrences": {$sum: 1}}}, {$sort: {_id: -1}} ).pretty(); 다음은 출력입니다.
{ "_id" : 139, "TotalOccurrences" : 2 }
{ "_id" : 128, "TotalOccurrences" : 1 }
{ "_id" : 125, "TotalOccurrences" : 1 }
{ "_id" : 110, "TotalOccurrences" : 1 }
{ "_id" : 98, "TotalOccurrences" : 1 } 사례 2 − 결과를 오름차순으로 원할 때마다. 쿼리는 다음과 같습니다 -
> db.aggregationSortDemo.aggregate( {$group: {_id: '$StudentId', "TotalOccurrences": {$sum: 1}}}, {$sort: {_id: 1}} ).pretty(); 다음은 출력입니다 -
{ "_id" : 98, "TotalOccurrences" : 1 }
{ "_id" : 110, "TotalOccurrences" : 1 }
{ "_id" : 125, "TotalOccurrences" : 1 }
{ "_id" : 128, "TotalOccurrences" : 1 }
{ "_id" : 139, "TotalOccurrences" : 2 }