Aloulou Ouagdi
Aloulou Ouagdi

Reputation: 3

Get max of a String value

I have a field "debit" stored in the database in the form of String while really it is a double/float. I wanted to get the maximum value of this field I started by doing :

    DBObject query = new BasicDBObject("debit", -1);
    d= collection.find.sort(query).limit(1); // for MAX

but unfortunately, it returns me a value which is not really the maximum value (returns 999.0 instead of 1432) I tried another solution by getting all the "debit" data in a list and get his max but I had this error

   List<Double> list = new ArrayList<>();
    while (d.hasNext()){
    if(!d.next().get("debit").toString().isEmpty()){
        list.add(Double.parseDouble(d.next().get("debit").toString()));

    }
        System.out.println(Collections.max(list));

    }

Error :

Exception in thread "main" java.lang.NumberFormatException: empty String

Normally i don't get this error beacause i make an if for empty value.

I except to get the maximum value of a field stored as String. Can someone propose me an idea or a resolution of my errors

Upvotes: 0

Views: 123

Answers (2)

Himanshu Sharma
Himanshu Sharma

Reputation: 3010

An optimum approach can be to do all processing work in the query itself. The following query can get us the expected output:

db.collection.aggregate([
    {
        $group:{
            "_id":null,
            "max":{
                $max:{
                    $toDouble: { 
                        $cond:[
                            {
                                $in:["$debit",["",null]]
                            },
                            "0",
                            "$debit"
                        ]
                    }
                }
            }
        }
    },
    {
        $project:{
            "_id":0
        }
    }
]).pretty()

Data set:

{ "_id" : ObjectId("5d619fadf00e0c8c3593b603"), "debit" : "999.0" }
{ "_id" : ObjectId("5d619fadf00e0c8c3593b604"), "debit" : "1432" }
{ "_id" : ObjectId("5d61a0daf00e0c8c3593b605"), "debit" : "997.0" }
{ "_id" : ObjectId("5d61a0daf00e0c8c3593b606"), "debit" : "" }

Output:

{ "max" : 1432 }

We are converting the debit into Double and calculating the max from converted values. If the debit is empty or null, then the conversion code would take it as 0.

Upvotes: 0

Niklas Lyszio
Niklas Lyszio

Reputation: 65

You get the next element twice. So after the first call, you get the first element (in your if Statement), and the second element in the Double.parseDouble()-Method. So you should change your code to:

List<Double> list = new ArrayList<>();
    while (d.hasNext()){
    String string = d.next().get("debit").toString();
    if(!string.isEmpty()){
       try{
        list.add(Double.parseDouble(string));
        } catch (NumberFormatException e) {
           e.printStackTrace(); //prints error
      }
    }
        System.out.println(Collections.max(list));

    }

Upvotes: 1

Related Questions