要获得标记的排序列表,请使用$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" ] }