查找MongoDB中重复的Name值的最高分?
若要查找最大分数,请使用GROUP()将集合中的文档分组。让我们创建一个包含文档的集合-
> db.demo114.insertOne({"Score":60,"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2efc57d8f64a552dae6354") } > db.demo114.insertOne({"Score":87,"Nam+e":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2efc5ad8f64a552dae6355") } > db.demo114.insertOne({"Score":45,"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2efc5dd8f64a552dae6356") } > db.demo114.insertOne({"Score":67,"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2efc68d8f64a552dae6357") } > db.demo114.insertOne({"Score":38,"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2efc74d8f64a552dae6358") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo114.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2efc57d8f64a552dae6354"), "Score" : 60, "Name" : "Chris" } { "_id" : ObjectId("5e2efc5ad8f64a552dae6355"), "Score" : 87, "Name" : "Chris" } { "_id" : ObjectId("5e2efc5dd8f64a552dae6356"), "Score" : 45, "Name" : "David" } { "_id" : ObjectId("5e2efc68d8f64a552dae6357"), "Score" : 67, "Name" : "Chris" } { "_id" : ObjectId("5e2efc74d8f64a552dae6358"), "Score" : 38, "Name" : "David" }
以下是查找最大值的查询。这将计算出重复名称值的最高得分,例如“Chris”和“David”-
> db.demo114.group( ... {key: {Name:true}, ... reduce: function(c,p) { ... if (p.maximumScore < c.Score) { ... p.maximumScore = c.Score; ... } ... }, ... initial: { maximumScore: 0 }} ... );
这将产生以下输出-
[ { "Name" : "Chris", "maximumScore" : 87 }, { "Name" : "David", "maximumScore" : 45 } ]