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

Aggregation MongoDB tính tổng giá sản phẩm theo ID tương tự

Sử dụng $group để gom nhóm theo Product_Id và $sum tính tổng giá. Tạo collection:

> db.aggreagateDemo.insertOne({"Product_Id":1,"ProductPrice":50});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06d3c025ddae1f53b621d9") }
> db.aggreagateDemo.insertOne({"Product_Id":2,"ProductPrice":100});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06d3c625ddae1f53b621da") }
> db.aggreagateDemo.insertOne({"Product_Id":2,"ProductPrice":500});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06d3cb25ddae1f53b621db") }
> db.aggreagateDemo.insertOne({"Product_Id":1,"ProductPrice":150});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06d3d125ddae1f53b621dc") }

Hiển thị tài liệu:

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

Aggregation gom theo Product_Id và tính tổng ProductPrice:

> db.aggreagateDemo.aggregate([
   { $group: {
      _id: "$Product_Id",
      TotalValue: { $sum: "$ProductPrice" }
   }}
]);

Kết quả - tổng giá theo từng sản phẩm:

Giải thích: $group với _id: "$Product_Id" tạo nhóm cho mỗi Product_Id duy nhất. $sum: "$ProductPrice" cộng dồn giá trong mỗi nhóm.