Devdit
 

MongoDB หาค่าเฉลี่ย AVG ด้วยคำสั่ง $avg

799

MongoDB หาค่าเฉลี่ย AVG ด้วยคำสั่ง $avg บทความนี้สอนใช้คำสั่ง $avg (Average) เพื่อหาค่าเฉลี่ยจาก field ที่ต้องการ ตัวอย่างหาค่าเฉลี่ยจาก field price ของ collection product สามารถเขียนคำสั่งได้ดังนี้

 

ตัวอย่าง ข้อมูลในตาราง หรือ collection ชื่อ product

{ name: 'Notebook', price: 200 }
{ name: 'Computer', price: 200 }
{ name: 'Mobile', price: 220 }
{ name: 'Super Computer', price: 400 }
{ name: 'Mouse', price: 100 }
{ name: 'MongoDB', price: 180 }

 

ตัวอย่าง MongoDB หาค่าเฉลี่ย AVG ด้วยคำสั่ง $avg

db.product.aggregate(
    [{
        $group:
        { 
            _id: null,
            avg: { $avg: "$price" }
        }
    }]
)

ผลลัพธ์

{ _id: mull, avg: 216.66666666666666 }

คำอธิบาย

MongoDB หาค่าเฉลี่ย AVG จากตัวอย่างใช้คำสั่ง aggregate ร่วมกับ collection product จากนั้นใช้คำสั่ง $group และหาค่าเฉลี่ยจาก field price ด้วยคำสั่ง avg: { $avg: "$price" } โดยตั้งชื่อผลลัพธ์ของ field ว่า avg

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ