MongoDB query to find the highest numeric value of a column?

MongoDBDatabaseBig Data Analytics

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.

raja
Published on 30-Apr-2019 10:28:12
Advertisements