MongoDB 聚合以获取两个分数最低的文档
为了获取分数的排序列表,请使用 $sort。使用 $limit: 2 仅显示两个分数最低的此类文档。我们创建一个包含文档的集合 -
> db.demo709.insertOne({Name:"John","Marks":75}); { "acknowledged" : true, "insertedId" : ObjectId("5ea839005d33e20ed1097b76") } > db.demo709.insertOne({Name:"Chris","Marks":45}); { "acknowledged" : true, "insertedId" : ObjectId("5ea839075d33e20ed1097b77") } > db.demo709.insertOne({Name:"David","Marks":54}); { "acknowledged" : true, "insertedId" : ObjectId("5ea839125d33e20ed1097b78") } > db.demo709.insertOne({Name:"Bob","Marks":69}); { "acknowledged" : true, "insertedId" : ObjectId("5ea839295d33e20ed1097b79") }
借助 find() 方法显示集合中的所有文档 -
> db.demo709.find();
这将产生以下输出 -
{ "_id" : ObjectId("5ea839005d33e20ed1097b76"), "Name" : "John", "Marks" : 75 } { "_id" : ObjectId("5ea839075d33e20ed1097b77"), "Name" : "Chris", "Marks" : 45 } { "_id" : ObjectId("5ea839125d33e20ed1097b78"), "Name" : "David", "Marks" : 54 } { "_id" : ObjectId("5ea839295d33e20ed1097b79"), "Name" : "Bob", "Marks" : 69 }
以下是获取两个分数最低的文档的查询 -
> db.demo709.aggregate({ ... $group: { ... _id: '$Marks', ... ListOfName: { $push: '$Name' } ... } ... }, { ... $sort: { ... '_id': 1 ... } ... }, { ... $limit: 2 ... });
这将产生以下输出 -
{ "_id" : 45, "ListOfName" : [ "Chris" ] } { "_id" : 54, "ListOfName" : [ "David" ] }
广告