ในการตรวจสอบว่ามีค่าสำหรับเขตข้อมูลในเอกสาร MongoDB หรือไม่ คุณสามารถใช้ find() พร้อมกับตัวดำเนินการ $exists ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.checkIfValueDemo.insertOne({"PlayerName":"John Smith","PlayerScores":[5000,98595858,554343]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc6f507af8e7a4ca6b2ad98")
}
> db.checkIfValueDemo.insertOne({"PlayerName":"John Doe","PlayerScores":[]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc6f512af8e7a4ca6b2ad99")
}
> db.checkIfValueDemo.insertOne({"PlayerName":"Carol Taylor","PlayerScores":[7848474,8746345353]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc6f521af8e7a4ca6b2ad9a")
}
> db.checkIfValueDemo.insertOne({"PlayerName":"David Miller","PlayerScores":[]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc6f531af8e7a4ca6b2ad9b")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -
> db.checkIfValueDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : ObjectId("5cc6f507af8e7a4ca6b2ad98"),
"PlayerName" : "John Smith",
"PlayerScores" : [
5000,
98595858,
554343
]
}
{
"_id" : ObjectId("5cc6f512af8e7a4ca6b2ad99"),
"PlayerName" : "John Doe",
"PlayerScores" : [ ]
}
{
"_id" : ObjectId("5cc6f521af8e7a4ca6b2ad9a"),
"PlayerName" : "Carol Taylor",
"PlayerScores" : [
7848474,
8746345353
]
}
{
"_id" : ObjectId("5cc6f531af8e7a4ca6b2ad9b"),
"PlayerName" : "David Miller",
"PlayerScores" : [ ]
} ต่อไปนี้เป็นแบบสอบถามเพื่อตรวจสอบว่ามีค่าสำหรับเขตข้อมูลในเอกสารหรือไม่ เรากำลังตรวจสอบฟิลด์ 'PlayerScores with value [ ] −
> db.checkIfValueDemo.find({'PlayerScores.0' : {$exists: true}}).count(); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
2