Bạn có thể sử dụng toán tử $ not cùng với $ type cho việc này. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> 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")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ bộ sưu tập với sự trợ giúp của phương thức find () -
> db.highestNumericValueOfAColumnDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_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"
} Sau đây là truy vấn để tìm giá trị số cao nhất của một cột -
> db.highestNumericValueOfAColumnDemo.find({StudentMathMarks: {$not: {$type:
2}}}).sort({StudentMathMarks: -1}).limit(1).pretty(); Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cba059d7219729fde21ddb3"),
"StudentName" : "Chris",
"StudentMathMarks" : 82
} Truy vấn trên bỏ qua giá trị chuỗi, vì vậy chúng tôi chỉ nhận được giá trị cao nhất của số nguyên là 82.