ใช้ $not ร่วมกับ $type เพื่อกรองเฉพาะค่าตัวเลข (BSON Type 1 = Double, 16 = Int32, 18 = Int64) แล้วค่อยเรียงหาค่าสูงสุด
ตัวอย่างการใช้งาน
สร้างคอลเลกชันผสมค่าตัวเลขและสตริง:
แสดงเอกสารทั้งหมด:
{ "_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" }หาค่าตัวเลขสูงสุด (ข้ามสตริง)
{ "_id" : ObjectId("5cba059d7219729fde21ddb3"), "StudentName" : "Chris", "StudentMathMarks" : 82 }คำอธิบาย:
{$type: 2}= String Type (BSON Type 2)$not: {$type: 2}= ไม่ใช่ String (คือตัวเลข).sort({StudentMathMarks: -1})เรียงมากไปน้อย.limit(1)เอาแค่ตัวแรก
หมายเหตุ: ใน MongoDB เวอร์ชันใหม่ ควรใช้ $type: "string" แทนตัวเลข 2 เพื่ออ่านง่ายกว่า