Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Aggregation MongoDB: Tính trung bình từ tài liệu và phần tử mảng

Pipeline phức tạp: Nhóm theo Information, unwind mảng details 2 lần, nhóm theo Name tính avg Marks, sắp xếp, nhóm lại gom kết quả. Tạo collection:

> db.demo598.insertOne({ Information:'Student', id:100, details:[{Name:'Chris',Marks:75},{Name:'Bob',Marks:55}] });
{ "acknowledged" : true, "insertedId" : ObjectId("5e947fccf5f1e70e134e2694") }
> db.demo598.insertOne({ Information:'Student', id:101, details:[{Name:'Chris',Marks:75},{Name:'Bob',Marks:45}] });
{ "acknowledged" : true, "insertedId" : ObjectId("5e947fcdf5f1e70e134e2695") }

Hiển thị dữ liệu:

> db.demo598.find();

Pipeline đầy đủ:

> db.demo598.aggregate([
...   { "$group": { "_id": "Information", "id": { "$avg": "$id" }, "details": { "$push": "$details" } } },
...   { "$unwind": "$details" }, { "$unwind": "$details" },
...   { "$group": { "_id": { "Information": "$_id", "Name": "$details.Name" }, "id": { "$avg": "$id" }, "AvgValue": { "$avg": "$details.Marks" } } },
...   { "$sort": { "_id": 1 } },
...   { "$group": { "_id": "$_id.Information", "id": { "$avg": "$id" }, "details": { "$push": { "Name": "$_id.Name", "MarksAvg": "$AvgValue" } } } }
... ]).pretty();

Kết quả (avg id=100.5, Chris avg Marks=75, Bob avg Marks=50):


Giải thích: 2 lần $unwind vì details là mảng trong mảng (do $push gom thành mảng mảng). Pipeline demo khả năng xử lý đa cấp phức tạp của aggregation.