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

Tìm giá trị cao nhất từ ​​mảng con trong tài liệu MongoDB?

Để tìm giá trị cao nhất từ ​​mảng con trong tài liệu, bạn có thể sử dụng khung tổng hợp. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu

> db.findHighestValueDemo.insertOne(
   ... {
      ... _id: 10001,
      ... "StudentDetails": [
         ... { "StudentName": "Chris", "StudentMathScore": 56},
         ... { "StudentName": "Robert", "StudentMathScore":47 },
         ... { "StudentName": "John", "StudentMathScore": 98 }]
   ... }
... );
{ "acknowledged" : true, "insertedId" : 10001 }
> db.findHighestValueDemo.insertOne(
   ... {
      ... _id: 10002,
      ... "StudentDetails": [
         ... { "StudentName": "Ramit", "StudentMathScore": 89},
         ... { "StudentName": "David", "StudentMathScore":76 },
         ... { "StudentName": "Bob", "StudentMathScore": 97 }
      ... ]
   ... }
... );
{ "acknowledged" : true, "insertedId" : 10002 }

Sau đây là truy vấn để 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.findHighestValueDemo.find().pretty();

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

{
   "_id" : 10001,
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentMathScore" : 56
      },
      {
         "StudentName" : "Robert",
         "StudentMathScore" : 47
      },
      {
         "StudentName" : "John",
         "StudentMathScore" : 98
      }
   ]
}
{
   "_id" : 10002,
   "StudentDetails" : [
      {
         "StudentName" : "Ramit",
         "StudentMathScore" : 89
      },
      {
         "StudentName" : "David",
         "StudentMathScore" : 76
      },
      {
         "StudentName" : "Bob",
         "StudentMathScore" : 97
      }
   ]
}

Sau đây là truy vấn để tìm giá trị cao nhất từ ​​các mảng con trong tài liệu

> db.findHighestValueDemo.aggregate([
   ... {$project:{"StudentDetails.StudentName":1, "StudentDetails.StudentMathScore":1}},
   ... {$unwind:"$StudentDetails"},
   ... {$sort:{"StudentDetails.StudentMathScore":-1}},
   ... {$limit:1}
... ]).pretty();

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

{
   "_id" : 10001,
   "StudentDetails" : {
      "StudentName" : "John",
      "StudentMathScore" : 98
   }
}