ในการตรวจสอบว่าฟิลด์เป็นตัวเลขใน MongoDB หรือไม่ ให้ใช้ตัวดำเนินการ $type ต่อไปนี้เป็นรูปแบบไวยากรณ์
db.yourCollectionName.find({youtFieldName: {$type:"number"}}).pretty(); ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน
> db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"John","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ec75dd628fa4220163b83")
}
>db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Chris","StudentMathScore":98,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ec77cd628fa4220163b84")
}
>db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Robert","StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ec7a4d628fa4220163b85")
}
>db.checkIfFieldIsNumberDemo.insertOne({"StudentId":101,"StudentName":"Larry","StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ec7ccd628fa4220163b86")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find()
> db.checkIfFieldIsNumberDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_id" : ObjectId("5c9ec75dd628fa4220163b83"),
"StudentName" : "John",
"StudentAge" : 23
}
{
"_id" : ObjectId("5c9ec77cd628fa4220163b84"),
"StudentName" : "Chris",
"StudentMathScore" : 98,
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c9ec7a4d628fa4220163b85"),
"StudentName" : "Robert",
"StudentCountryName" : "AUS"
}
{
"_id" : ObjectId("5c9ec7ccd628fa4220163b86"),
"StudentId" : 101,
"StudentName" : "Larry",
"StudentCountryName" : "AUS"
} ต่อไปนี้เป็นแบบสอบถามเพื่อตรวจสอบว่าเขตข้อมูลเป็นตัวเลขหรือไม่
> db.checkIfFieldIsNumberDemo.find({StudentMathScore: {$type:"number"}}).pretty(); ต่อไปนี้เป็นผลลัพธ์ที่แสดงฟิลด์ที่เป็นตัวเลข เช่น StudentMathScore
{
"_id" : ObjectId("5c9ec77cd628fa4220163b84"),
"StudentName" : "Chris",
"StudentMathScore" : 98,
"StudentCountryName" : "US"
}