หากต้องการใช้กลุ่ม $ หลายระดับ ให้ใช้ MongoDB รวม ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo76.insertOne({ Name:"Chris","Age" : 21, "CountryName" : 'US' }); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd3e571bf0181ecc42281") } > db.demo76.insertOne({ Name:"Chris","Age" : 21, "CountryName" : 'US' }); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd3e571bf0181ecc42282") } > db.demo76.insertOne({ Name:"Chris","Age" : 23, "CountryName" : 'UK' }); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd3e571bf0181ecc42283") } > db.demo76.insertOne({ Name:"Chris","Age" : 23, "CountryName" : 'UK' }); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd3e571bf0181ecc42284") } > db.demo76.insertOne({ Name:"Chris","Age" : 21, "CountryName" : 'AUS' }); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd3e571bf0181ecc42285") } > db.demo76.insertOne({ Name:"Chris","Age" : 21, "CountryName" : 'AUS' }); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd3e571bf0181ecc42286") } > db.demo76.insertOne({ Name:"Chris","Age" : 23, "CountryName" : 'AUS' }); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd3e571bf0181ecc42287") } > db.demo76.insertOne({ Name:"Chris","Age" : 21, "CountryName" : 'UK' }); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd3e571bf0181ecc42288") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo76.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e2bd3e571bf0181ecc42281"), "Name" : "Chris", "Age" : 21, "CountryName" : "US" } { "_id" : ObjectId("5e2bd3e571bf0181ecc42282"), "Name" : "Chris", "Age" : 21, "CountryName" : "US" } { "_id" : ObjectId("5e2bd3e571bf0181ecc42283"), "Name" : "Chris", "Age" : 23, "CountryName" : "UK" } { "_id" : ObjectId("5e2bd3e571bf0181ecc42284"), "Name" : "Chris", "Age" : 23, "CountryName" : "UK" } { "_id" : ObjectId("5e2bd3e571bf0181ecc42285"), "Name" : "Chris", "Age" : 21, "CountryName" : "AUS" } { "_id" : ObjectId("5e2bd3e571bf0181ecc42286"), "Name" : "Chris", "Age" : 21, "CountryName" : "AUS" } { "_id" : ObjectId("5e2bd3e571bf0181ecc42287"), "Name" : "Chris", "Age" : 23, "CountryName" : "AUS" } { "_id" : ObjectId("5e2bd3e571bf0181ecc42288"), "Name" : "Chris", "Age" : 21, "CountryName" : "UK" }
ต่อไปนี้เป็นแบบสอบถามเพื่อใช้ $group หลายระดับ -
> db.demo76.aggregate([ ... { "$match": { "Name": "Chris" }}, ... { "$group": { ... "_id": { "Age": "$Age", "CountryName": "$CountryName" }, ... "count": { "$sum": 1 } ... }}, ... { "$group": { ... "_id": "$_id.Age", ... "CountryName": { ... "$push": { ... "k": "$_id.CountryName", ... "v": "$count" ... } ... } ... }}, ... { "$addFields": { ... "CountryName": { ... "$arrayToObject": "$CountryName" ... } ... }} ... ]);
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : 23, "CountryName" : { "AUS" : 1, "UK" : 2 } } { "_id" : 21, "CountryName" : { "UK" : 1, "AUS" : 2, "US" : 2 } }