Computer >> Máy Tính >  >> Lập trình >> MongoDB

Tìm điểm tối đa cho các giá trị Tên trùng lặp trong MongoDB?

Để tìm điểm tối đa, hãy sử dụng GROUP () để nhóm các tài liệu trong một bộ sưu tập. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> 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")
}

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

> db.demo114.find();

Điều này sẽ tạo ra kết quả sau -

{ "_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" }

Sau đây là truy vấn để tìm tối đa. Điều này tính toán điểm tối đa của các giá trị tên trùng lặp, chẳng hạn như “Chris” và “David” -

> db.demo114.group(
...    {key: {Name:true},
...    reduce: function(c,p) {
...       if (p.maximumScore < c.Score) {
...          p.maximumScore = c.Score;
...       }
...    },
...    initial: { maximumScore: 0 }}
... );

Điều này sẽ tạo ra kết quả sau -

[
   {
      "Name" : "Chris",
      "maximumScore" : 87
   },
   {
      "Name" : "David",
      "maximumScore" : 45
   }
]