Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

MongoDB aggregate: tổng giá trị theo tên trong mảng lồng nhau

Tính tổng Score cho mỗi Name trong mảng OtherDetails lồng trong StudentDetails across các document.

Tạo collection demo126:

> db.demo126.insertOne({
   "StudentDetails": {
      "Number": 1,
      "OtherDetails": [ {"Name":"Chris","Score":55} ]
   }
});
> db.demo126.insertOne({
   "StudentDetails": {
      "Number": 2,
      "OtherDetails": [
         {"Name":"Chris","Score":35},
         {"Name":"David","Score":87}
      ]
   }
});

Pipeline: unwind OtherDetails, group theo Name tính sum Score:

> db.demo126.aggregate([
   { $unwind: "$StudentDetails.OtherDetails" },
   {
      $group: {
         _id: "$StudentDetails.OtherDetails.Name",
         quantity: { $sum: "$StudentDetails.OtherDetails.Score" }
      }
   }
])

Kết quả: Chris = 90, David = 87:

{ "_id" : "David", "quantity" : 87 }
{ "_id" : "Chris", "quantity" : 90 }