如何在 MongoDB 中執行聚合排序?


為此,可以使用 aggregate() 方法和 $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 }

更新於: 2019 年 7 月 30 日

207 次瀏覽

開啟你的 事業

完成課程獲得認證

開始
廣告