如何使用 MongoDB 选取每个组中的最大值?
可以使用 $group。让我们创建一个包含文档的集合 −
> db.demo659.insertOne({Name:"Chris",CountryName:"US","Marks":50}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1a50724113ea5458c7cf9") } > db.demo659.insertOne({Name:"David",CountryName:"US","Marks":60}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1a50724113ea5458c7cfa") } > db.demo659.insertOne({Name:"Mike",CountryName:"US","Marks":55}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1a50724113ea5458c7cfb") } > db.demo659.insertOne({Name:"Chris",CountryName:"UK","Marks":75}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1a50724113ea5458c7cfc") } > db.demo659.insertOne({Name:"David",CountryName:"UK","Marks":54}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1a50724113ea5458c7cfd") } > db.demo659.insertOne({Name:"Mike",CountryName:"UK","Marks":72}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1a50824113ea5458c7cfe") }
借助 find() 方法来显示集合中的所有文档 −
> db.demo659.find();
这将生成以下输出。它查找每个文档(即 CountryName US 和 UK)中的最高分 −
{ "_id" : ObjectId("5ea1a50724113ea5458c7cf9"), "Name" : "Chris", "CountryName" : "US", "Marks" : 50 } { "_id" : ObjectId("5ea1a50724113ea5458c7cfa"), "Name" : "David", "CountryName" : "US", "Marks" : 60 } { "_id" : ObjectId("5ea1a50724113ea5458c7cfb"), "Name" : "Mike", "CountryName" : "US", "Marks" : 55 } { "_id" : ObjectId("5ea1a50724113ea5458c7cfc"), "Name" : "Chris", "CountryName" : "UK", "Marks" : 75 } { "_id" : ObjectId("5ea1a50724113ea5458c7cfd"), "Name" : "David", "CountryName" : "UK", "Marks" : 54 } { "_id" : ObjectId("5ea1a50824113ea5458c7cfe"), "Name" : "Mike", "CountryName" : "UK", "Marks" : 72 }
以下是查询以选择每个组中的最大值 −
> db.demo659.aggregate( { $group: { ... _id: {CountryName: "$CountryName" }, ... 'MaxMarks': { $max : "$Marks" } ... }})
这将生成以下输出 −
{ "_id" : { "CountryName" : "UK" }, "MaxMarks" : 75 } { "_id" : { "CountryName" : "US" }, "MaxMarks" : 60 }
广告