在MongoDB中执行聚合排序?
您可以将aggregate()
method和$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()
method的帮助下显示集合中的所有文档。查询如下-
> 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 }