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

การทำ Aggregation บน Nested Documents ใน MongoDB

Aggregation บน Nested Documents ลึกด้วย $unwind และ $group

บทความนี้สาธิตการทำ Aggregation บนโครงสร้าง Nested Documents ที่ซับซ้อน (Array of Objects of Arrays) โดยใช้ $unwind หลายขั้นตอนเพื่อ Flatten โครงสร้าง แล้ว $group คำนวณค่าสูงสุด ($max)

ขั้นตอนที่ 1: สร้าง Collection และเพิ่มข้อมูลตัวอย่าง

สร้าง collection aggregateDemo มี ProductInformation เป็นอาร์เรย์ของออบเจกต์ที่มี Product1 เป็นอาร์เรย์ของออบเจกต์ที่มี Amount

> db.aggregateDemo.insertOne({
    "ProductInformation": [
        { "Product1": [{ "Amount": 50 }, { "Amount": 90 }, { "Amount": 30 }] },
        { "Product1": [{ "Amount": 200 }, { "Amount": 30 }, { "Amount": 40 }] },
        { "Product1": [{ "Amount": 150 }, { "Amount": 190 }, { "Amount": 198 }] }
    ]
});
{ "acknowledged": true, "insertedId": ObjectId("5e04df58150ee0e76c06a04d") }
// ... insert อีก 1 เอกสารที่มี Amount สูงถึง 1002

ขั้นตอนที่ 2: แสดงข้อมูลทั้งหมด

> db.aggregateDemo.find().pretty();

ขั้นตอนที่ 3: Aggregation Pipeline หา Amount สูงสุด

  1. $unwind: "$ProductInformation" - แยกระดับ 1
  2. $unwind: "$ProductInformation.Product1" - แยกระดับ 2 (เข้าไปในอาร์เรย์ Product1)
  3. $group - จัดกลุ่มทั้งหมด (_id: null) หา $max ของ ProductInformation.Product1.Amount
> db.aggregateDemo.aggregate([
    { $unwind: "$ProductInformation" },
    { $unwind: "$ProductInformation.Product1" },
    { $group: { _id: null, MaximumAmount: { $max: "$ProductInformation.Product1.Amount" } } }
]);

ผลลัพธ์ที่ได้

{ "_id": null, "MaximumAmount": 1002 }

สรุป: การ $unwind หลายขั้นตอน (Multiple $unwind) เป็นเทคนิคหลักในการ Flatten Nested Arrays เพื่อให้เข้าถึงฟิลด์ลึกได้ใน $group หรือ $project