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

MongoDB Query: การคำนวณค่าเฉลี่ย (Average)

การคำนวณค่าเฉลี่ยของ field ที่อยู่ใน nested object สามารถทำได้ด้วย $avg ใน aggregate pipeline โดยระบุ path ไปยัง field นั้น

สร้างคอลเลกชันและข้อมูลตัวอย่าง

> db.demo80.insertOne({"Details":{"Price":10.5}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bf43271bf0181ecc42297") }
> db.demo80.insertOne({"Details":{"Price":50.3}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bf43871bf0181ecc42298") }
> db.demo80.insertOne({"Details":{"Price":100.10}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bf43f71bf0181ecc42299") }

แสดงข้อมูลทั้งหมด

> db.demo80.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e2bf43271bf0181ecc42297"), "Details" : { "Price" : 10.5 } }
{ "_id" : ObjectId("5e2bf43871bf0181ecc42298"), "Details" : { "Price" : 50.3 } }
{ "_id" : ObjectId("5e2bf43f71bf0181ecc42299"), "Details" : { "Price" : 100.1 } }

Query คำนวณค่าเฉลี่ยราคา

> db.demo80.aggregate([
... {
...   "$group": {
...     "_id": null,
...     "AvgValue": {
...       "$avg": "$Details.Price"
...     }
...   }
... }
... ]);

คำอธิบาย:

  • "$Details.Price": ใช้ dot notation เข้าถึง field Price ภายใน object Details
  • "_id": null: จัดกลุ่มเอกสารทั้งหมดเป็นกลุ่มเดียว

ผลลัพธ์

{ "_id" : null, "AvgValue" : 53.633333333333326 }

ค่าเฉลี่ย = (10.5 + 50.3 + 100.1) / 3 = 53.63

การประยุกต์ใช้: ค่าเฉลี่ยแยกตามกลุ่ม

หากมี field Category และต้องการค่าเฉลี่ยแยกตามหมวดหมู่:

db.demo80.aggregate([
  {
    $group: {
      "_id": "$Details.Category",
      "AvgPrice": { $avg: "$Details.Price" }
    }
  }
])

หมายเหตุ: $avg จะข้ามค่า null และ missing values อัตโนมัติ