Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

MongoDB Aggregate: รวมคะแนนตามชื่อในอาร์เรย์แบบฝังข้ามเอกสาร


สร้างคอลเลกชันตัวอย่าง

> db.demo126.insertOne(
  {
    "StudentDetails": {
      "Number": 1,
      "OtherDetails": [
        { "Name": "Chris", "Score": 55 }
      ]
    }
  }
);
{ "acknowledged": true, "insertedId": ObjectId("5e304b3068e7f832db1a7f56") }
> db.demo126.insertOne(
  {
    "StudentDetails": {
      "Number": 2,
      "OtherDetails": [
        { "Name": "Chris", "Score": 35 },
        { "Name": "David", "Score": 87 }
      ]
    }
  }
);
{ "acknowledged": true, "insertedId": ObjectId("5e304b3068e7f832db1a7f57") }

แสดงข้อมูล

> db.demo126.find();
{ "_id": ObjectId("5e304b3068e7f832db1a7f56"), "StudentDetails": { "Number": 1, "OtherDetails": [ { "Name": "Chris", "Score": 55 } ] } }
{ "_id": ObjectId("5e304b3068e7f832db1a7f57"), "StudentDetails": { "Number": 2, "OtherDetails": [ { "Name": "Chris", "Score": 35 }, { "Name": "David", "Score": 87 } ] } }

คิวรี Aggregate: $unwind + $group

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

ผลลัพธ์: Chris=90, David=87

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