- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to find the highest numeric value of a column?
You can use $not operator along with $type for this. Let us first create a collection with documents −
> 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") }
Following is the query to display all documents from the collection with the help of find() method −
> db.highestNumericValueOfAColumnDemo.find().pretty();
This will produce the following output −
{ "_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" }
Following is the query to find the highest numeric value of a column −
> db.highestNumericValueOfAColumnDemo.find({StudentMathMarks: {$not: {$type: 2}}}).sort({StudentMathMarks: -1}).limit(1).pretty();
This will produce the following output −
{ "_id" : ObjectId("5cba059d7219729fde21ddb3"), "StudentName" : "Chris", "StudentMathMarks" : 82 }
The above query ignores the string value, so we are getting only the integer highest value which is 82.
Advertisements