ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo586.insertOne( ... {"details": [ ... { ... "Name":"Chris", ... "Marks":71 ... }, ... { ... "Name":"Chris", ... "Marks":61 ... }, ... { ... "Name":"David", ... "Marks":81 ... } ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9200fefd2d90c177b5bcc7") } > db.demo586.insertOne( ... {"details": [ ... { ... "Name":"Chris", ... "Marks":71 ... }, ... { ... "Name":"Carol", ... "Marks":61 ... }, ... { ... "Name":"David", ... "Marks":81 ... } ... ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9200fefd2d90c177b5bcc8") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo586.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e9200fefd2d90c177b5bcc7"), "details" : [ { "Name" : "Chris", "Marks" : 71 }, { "Name" : "Chris", "Marks" : 61 }, { "Name" : "David", "Marks" : 81 } ] } { "_id" : ObjectId("5e9200fefd2d90c177b5bcc8"), "details" : [ { "Name" : "Chris", "Marks" : 71 }, { "Name" : "Carol", "Marks" : 61 }, { "Name" : "David", "Marks" : 81 } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อเลือกอย่างชัดเจนและนับ -
> var q= [ ... { "$unwind": "$details" }, ... { ... "$group": { ... "_id": { ... "Name": "$details.Name", ... "Marks": "$details.Marks" ... }, ... "count": { "$sum": 1 } ... } ... }, ... { ... "$group": { ... "_id": "$_id.Name", ... "distinctV": { ... "$addToSet": { ... "value": "$_id.Marks", ... "numberOfValues": "$count" ... } ... } ... } ... }, ... { ... "$project": { ... "_id": 0, ... "Name": "$_id", ... "distinctV": 1 ... } ... } ... ]; > db.demo586.aggregate(q);
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "distinctV" : [ { "value" : 61, "numberOfValues" : 1 } ], "Name" : "Carol" } { "distinctV" : [ { "value" : 71, "numberOfValues" : 2 }, { "value" : 61, "numberOfValues" : 1 } ], "Name" : "Chris" } { "distinctV" : [ { "value" : 81, "numberOfValues" : 2 } ], "Name" : "David" }