Để nhóm các mục trong mảng, hãy sử dụng $unwind để tách mảng, sau đó $group theo giá và $sort để sắp xếp.
Tạo collection với mảng ProductInformation:
> db.demo566.insertOne(
... {
... "ProductInformation" : [
... { "ProductName" : "Product-1", "ProductPrice" :100 },
... { "ProductName" : "Product-2", "ProductPrice" :1100 },
... { "ProductName" : "Product-3", "ProductPrice" :100 },
... { "ProductName" : "Product-4", "ProductPrice" :1100 },
... { "ProductName" : "Product-5", "ProductPrice" :100 }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5e908e2339cfeaaf0b97b57a") }
Hiển thị tài liệu:
> db.demo566.find();
Pipeline aggregate: unwind mảng, group theo ProductPrice đếm số lượng, sort theo _id (giá):
> db.demo566.aggregate([
... { "$unwind": "$ProductInformation" },
... { "$group": { "_id": "$ProductInformation.ProductPrice", "Value": { "$sum" : 1 } } },
... { "$sort": { "_id" :1 } }
... ])
Kết quả (giá 100: 3 sản phẩm, giá 1100: 2 sản phẩm):
{ "_id" : 100, "Value" : 3 }
{ "_id" : 1100, "Value" : 2 }