Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

จัดกลุ่มอิลิเมนต์อาร์เรย์ใน MongoDB และนับจำนวนสินค้าที่มีราคาใกล้เคียง


เพื่อจัดกลุ่มอิลิเมนต์อาร์เรย์ ให้ใช้ $group ร่วมกับ $sort มาสร้างคอลเลกชันพร้อมเอกสารกันก่อน

> 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") }

แสดงเอกสารทั้งหมดจากคอลเลกชันด้วยเมธอด find()

> db.demo566.find();

จะได้ผลลัพธ์ดังนี้

{ "_id" : ObjectId("5e908e2339cfeaaf0b97b57a"), "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 } ] }

คำสั่งสำหรับจัดกลุ่มอิลิเมนต์อาร์เรย์

> db.demo566.aggregate([ ... { ...    "$unwind": "$ProductInformation" ... }, ... { ...    "$group": { ...       "_id": "$ProductInformation.ProductPrice", ...       "Value": { "$sum" : 1 } ...    } ... }, ... { "$sort": { "_id" :1 } } ... ])

จะได้ผลลัพธ์ดังนี้

{ "_id" : 100, "Value" : 3 } { "_id" : 1100, "Value" : 2 }