คุณสามารถใช้ตัวดำเนินการ $not ร่วมกับ $type สำหรับสิ่งนี้ ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.highestNumericValueOfAColumnDemo.insertOne(
... {
... "StudentName": "John",
... "StudentMathMarks":69
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cba05727219729fde21ddb1")
}
> db.highestNumericValueOfAColumnDemo.insertOne(
... {
... "StudentName": "Carol",
... "StudentMathMarks":"89"
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cba059d7219729fde21ddb2")
}
> db.highestNumericValueOfAColumnDemo.insertOne(
... {
... "StudentName": "Chris",
... "StudentMathMarks":82
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cba059d7219729fde21ddb3")
}
> db.highestNumericValueOfAColumnDemo.insertOne(
... {
... "StudentName": "John",
... "StudentMathMarks":"100"
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cba059d7219729fde21ddb4")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -
> db.highestNumericValueOfAColumnDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : ObjectId("5cba05727219729fde21ddb1"),
"StudentName" : "John",
"StudentMathMarks" : 69
}
{
"_id" : ObjectId("5cba059d7219729fde21ddb2"),
"StudentName" : "Carol",
"StudentMathMarks" : "89"
}
{
"_id" : ObjectId("5cba059d7219729fde21ddb3"),
"StudentName" : "Chris",
"StudentMathMarks" : 82
}
{
"_id" : ObjectId("5cba059d7219729fde21ddb4"),
"StudentName" : "John",
"StudentMathMarks" : "100"
} ต่อไปนี้เป็นแบบสอบถามเพื่อค้นหาค่าตัวเลขสูงสุดของคอลัมน์ -
> db.highestNumericValueOfAColumnDemo.find({StudentMathMarks: {$not: {$type:
2}}}).sort({StudentMathMarks: -1}).limit(1).pretty(); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : ObjectId("5cba059d7219729fde21ddb3"),
"StudentName" : "Chris",
"StudentMathMarks" : 82
} แบบสอบถามด้านบนละเว้นค่าสตริง ดังนั้นเราจึงได้รับเฉพาะค่าสูงสุดของจำนวนเต็มซึ่งก็คือ 82