สำหรับสิ่งนี้ ให้ใช้เครื่องหมายจุดร่วมกับ $group ใน MongoDB ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo617.insertOne(
... {
...
... "clientDetails": {
... "Name": "Chris",
... "Age":32,
... "Project":"Online Library Management System"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e99d2b86c954c74be91e69b")
}
>
> db.demo617.insertOne(
... {
...
... "clientDetails": {
... "Name": "David",
... "Age":34,
... "Project":"Online Hospital Management System"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e99d2b86c954c74be91e69c")
}
>
> db.demo617.insertOne(
... {
...
... "clientDetails": {
... "Name": "David",
... "Age":34,
... "Project":"Online Library Management System"
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e99d2b96c954c74be91e69d")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo617.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e99d2b86c954c74be91e69b"), "clientDetails" : { "Name" : "Chris", "Age" : 32, "Project" : "Online Library Management System" } }
{ "_id" : ObjectId("5e99d2b86c954c74be91e69c"), "clientDetails" : { "Name" : "David", "Age" : 34, "Project" : "Online Hospital Management System" } }
{ "_id" : ObjectId("5e99d2b96c954c74be91e69d"), "clientDetails" : { "Name" : "David", "Age" : 34, "Project" : "Online Library Management System" } } แบบสอบถามกลุ่มตามวัตถุที่ซ้อนกันใน MongoDB -
> db.demo617.aggregate({ $group : {_id : "$clientDetails.Project", All : { $sum : 1 }} }); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : "Online Hosiptal Management System", "All" : 1 }
{ "_id" : "Online Library Management System", "All" : 2 }