您可以使用$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美国和英国)中找到最大分数-
{ "_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 }