在 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 } ]
广告