คุณสามารถดำเนินการที่แตกต่างกับหลาย ๆ คีย์ด้วยความช่วยเหลือของเฟรมเวิร์กรวม
เพื่อให้เข้าใจแนวคิด ให้เราสร้างคอลเลกชันพร้อมกับเอกสาร แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Mike","StudentAge":22,"StudentMathMarks":56});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f74488d10a061296a3c53")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Mike","StudentAge":22,"StudentMathMarks":56});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f744b8d10a061296a3c54")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":45});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f74598d10a061296a3c55")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":45});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f745e8d10a061296a3c56")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Carol","StudentAge":27,"StudentMathMarks":54});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f74688d10a061296a3c57")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังต่อไปนี้ −
> db.distinctWithMultipleKeysDemo.find().pretty();
ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c7f74488d10a061296a3c53"),
"StudentName" : "Mike",
"StudentAge" : 22,
"StudentMathMarks" : 56
}
{
"_id" : ObjectId("5c7f744b8d10a061296a3c54"),
"StudentName" : "Mike",
"StudentAge" : 22,
"StudentMathMarks" : 56
}
{
"_id" : ObjectId("5c7f74598d10a061296a3c55"),
"StudentName" : "Bob",
"StudentAge" : 23,
"StudentMathMarks" : 45
}
{
"_id" : ObjectId("5c7f745e8d10a061296a3c56"),
"StudentName" : "Bob",
"StudentAge" : 23,
"StudentMathMarks" : 45
}
{
"_id" : ObjectId("5c7f74688d10a061296a3c57"),
"StudentName" : "Carol",
"StudentAge" : 27,
"StudentMathMarks" : 54
} นี่คือแบบสอบถามเพื่อดำเนินการที่แตกต่างกับหลายคีย์ -
> c = db.distinctWithMultipleKeysDemo;
test.distinctWithMultipleKeysDemo
> myResult = c.aggregate( [ {"$group": { "_id": { StudentName:"$StudentName", StudentAge: "$StudentAge" } } } ] ); ต่อไปนี้เป็นผลลัพธ์ -
{ "_id" : { "StudentName" : "Carol", "StudentAge" : 27 } }
{ "_id" : { "StudentName" : "Bob", "StudentAge" : 23 } }
{ "_id" : { "StudentName" : "Mike", "StudentAge" : 22 } }