ในการเลือกระเบียนที่มีคีย์ที่กำหนด คุณสามารถใช้ตัวดำเนินการ $exists ไวยากรณ์มีดังนี้ −
db.yourCollectionName.find( { yourFieldName: { $exists : true } } ).pretty(); เพื่อให้เข้าใจไวยากรณ์ข้างต้น ให้เราสร้างคอลเลกชันด้วยเอกสาร แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentMathMarks":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8b7be780f10143d8431e0f")
}
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Carol","StudentMathMarks":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8b7bfc80f10143d8431e10")
}
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Sam","StudentAge":26,"StudentMathMarks":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8b7c1280f10143d8431e11")
}
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Sam","StudentMathMarks":98});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8b7c2180f10143d8431e12")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังนี้ −
> db.selectRecordsHavingKeyDemo.find().pretty();
ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c8b7be780f10143d8431e0f"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentMathMarks" : 78
}
{
"_id" : ObjectId("5c8b7bfc80f10143d8431e10"),
"StudentName" : "Carol",
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c1280f10143d8431e11"),
"StudentName" : "Sam",
"StudentAge" : 26,
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c2180f10143d8431e12"),
"StudentName" : "Sam",
"StudentMathMarks" : 98
} นี่คือแบบสอบถามเพื่อเลือกระเบียนที่มีคีย์ที่กำหนด -
> db.selectRecordsHavingKeyDemo.find( { StudentMathMarks : { $exists : true } } ).pretty(); ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c8b7be780f10143d8431e0f"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentMathMarks" : 78
}
{
"_id" : ObjectId("5c8b7bfc80f10143d8431e10"),
"StudentName" : "Carol",
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c1280f10143d8431e11"),
"StudentName" : "Sam",
"StudentAge" : 26,
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c8b7c2180f10143d8431e12"),
"StudentName" : "Sam",
"StudentMathMarks" : 98
}