Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.