Toán tử $avg trong aggregation pipeline tính trung bình cộng của các giá trị số trên nhóm tài liệu. Kết hợp với $group để tính trung bình toàn collection hoặc theo nhóm.
Dữ liệu mẫu
> db.demo159.insertOne({"Score":50});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3557b2fdf09dd6d0853a01") }
> db.demo159.insertOne({"Score":70});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3557b6fdf09dd6d0853a02") }
> db.demo159.insertOne({"Score":60});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3557c4fdf09dd6d0853a03") }
Xem dữ liệu
> db.demo159.find();
{ "_id" : ObjectId("5e3557b2fdf09dd6d0853a01"), "Score" : 50 }
{ "_id" : ObjectId("5e3557b6fdf09dd6d0853a02"), "Score" : 70 }
{ "_id" : ObjectId("5e3557c4fdf09dd6d0853a03"), "Score" : 60 }
Tính trung bình Score
> db.demo159.aggregate([{$group: {_id:null, AverageValue: {$avg:"$Score"} } }])
Kết quả
{ "_id" : null, "AverageValue" : 60 }
Giải thích: _id: null nghĩa là nhóm tất cả tài liệu thành một nhóm duy nhất. $avg: "$Score" tính trung bình trường Score. Kết quả: (50+70+60)/3 = 60. Để tính trung bình theo nhóm (ví dụ theo lớp), thay _id: null bằng _id: "$Class".