gaurav singh
gaurav singh

Reputation: 1416

I am unable to Fetch data from mongoDB while whn i using BigDecimal inside query

     BigDecimal log_max=new BigDecimal(21.11617279052734);
         BigDecimal log_min=new BigDecimal(21.01617279052734);
         BigDecimal lat_max=new BigDecimal(61.43435454343454);
         BigDecimal lat_min=new BigDecimal(61.03435454343454);
         String col_name="latitude";
         String col_name2="longitude";
         List<BasicDBObject> criteria=new ArrayList<BasicDBObject>();
         BasicDBObject searchQuery1 =new BasicDBObject(col_name, new BasicDBObject("$gte", lat_min).append("$lte",  lat_max));
         criteria.add(searchQuery1);
         BasicDBObject searchQuery2=new BasicDBObject(col_name2, new BasicDBObject("$gte", log_min).append("$lte",  log_max));
         criteria.add(searchQuery2); 

         DBCursor cursor = coll.find(query); 
         while (cursor.hasNext()) { 
                DBObject cursorObj = cursor.next();                 
              LOGGER.info("Collection  successf");  
                Object temp1 = cursorObj.get("longitude");
                BigDecimal longitude = new BigDecimal(temp1.toString());
                System.out.println("longitude ::::"+longitude);
                Object temp2 =cursorObj.get("latitude");
                BigDecimal latitude = new BigDecimal(temp2.toString());
                 LOGGER.info("done getting ");

          }
}

I'm getting java.lang.IllegalArgumentException: can't serialize class java.math.BigDecimal

Does anybody know what will be alernative of BigDecimal....

Upvotes: 1

Views: 706

Answers (1)

Hardik Modha
Hardik Modha

Reputation: 12736

By going through some of the materials available on the internet, I'll try to provide a concise answer to you question.

First thing, BigDecimal is not supported natively by MongoDB so you can't use BigDecimal directly. So how to deal with it?

Well, There are alternatives.

  1. Convert your BigDecimal value to String and store in the database. If you are using spring-data then it will be taken care of. But storing as String doesn't work as expected and might give you unexpected results on aggregation queries.
  2. If you think that using Double will suffice then you can either use Double or if you want to use BigDecimal then you can write your custom converter in spring-data-mongodb, which will convert your BigDecimal to Double when storing in the database and Double to BigDecimal when reading from it. You can check this answer for an example.
  3. You can write your custom type and use it. You can check this and this.

Upvotes: 2

Related Questions