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

Aggregation: จัดกลุ่มวันที่ในเอกสารซ้อนกัน (Nested Object) และนับจำนวน


สำหรับการรวมข้อมูล (Aggregation) ให้ใช้ aggregate() ใน MongoDB จัดกลุ่มวันที่ด้วย $group มาสร้างคอลเล็กชันกันเถอะ

> db.demo717.insertOne(
    {
        "shippingdetails":
        [
            {
                duedate:"2020-04-29 22:33:04"
            },
            {
                duedate:"2020-03-29 22:33:04"
            },
            {
                duedate:"2020-04-29 22:33:04"
            },
            {
                duedate:"2020-01-29 22:33:04"
            }
        ]
    }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5ea9b3cd85324c2c98cc4c30") }

แสดงเอกสารทั้งหมดด้วยเมธอด find()

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

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

{ "_id" : ObjectId("5ea9b3cd85324c2c98cc4c30"), "shippingdetails" : [ { "duedate" : "2020-04-29 22:33:04" }, { "duedate" : "2020-03-29 22:33:04" }, { "duedate" : "2020-04-29 22:33:04" }, { "duedate" : "2020-01-29 22:33:04" } ] }

คำสั่ง Aggregation สำหรับจัดกลุ่มวันที่ในเอกสารซ้อนกัน

> db.demo717.aggregate(
    {
        $unwind:"$shippingdetails"
    },
    {
        $group: {
            _id: "$shippingdetails.duedate",
            count: {
                $sum: 1
            }
        }
    }
)

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

{ "_id" : "2020-01-29 22:33:04", "count" : 1 }
{ "_id" : "2020-03-29 22:33:04", "count" : 1 }
{ "_id" : "2020-04-29 22:33:04", "count" : 2 }