mongodb double 精度解决方案

mongodb double精度问题所学到的知识

背景介绍:

由于目前本人在做一个涉及计费的一个项目,中间有统计计费,比如一个公司合同下 每个账号的每天/每月的消费情况。
比如查今天的流水账,统计费用最先想到的是mongodb的聚合函数match group sum ,由于金额大部分有小数点,就搞了double 类型,那么问题来了,java的double计算都是有精度问题的,比如99.3 – 0.2的结果99.0999999999.

方案改进:

mongodb 对double 聚合sum 的结果也是如此,毕竟硬件对double 精度就这样了。

List<Document> pipeline = Arrays.asList(new Document("$match", map),
              new Document("$group", new Document("_id", "$" + BaseInfoSo.CONT_ID).append("totalExpense",
                      new Document("$sum", "$" + BaseInfoSo.EXPENSE))));
      AggregateIterable<Document> iterable = collection.aggregate(pipeline);

然后就只能把每次消费拿出来自己统计,这时候用到的是addToSet / push,刚开始用了addToSet 感觉不对,然后发现addToSet是去重复的,push可重复的。
就用了push。拿出来后再用bigDecimal计算。

List<Document> pipeline = Arrays.asList(new Document("$match", map),
                new Document("$group", new Document("_id", "$" + BaseInfoSo.CONT_ID).append("eachExpense",
                        new Document("$push", "$" + BaseInfoSo.EXPENSE))));
        AggregateIterable<Document> iterable = collection.aggregate(pipeline);

由于用到了mongodb的增量更新费用,但是mongodb对double的更新同样是存在精度问题

Bson filter = Filters.eq(BaseInfoSo.CONT_ID,dto.getContId());
            Document doc = new Document("$inc", new Document(BaseInfoSo.CALL_TIMES, 1)
                    .append(BaseInfoSo.BALANCE, -dto.getExpense()))
                    .append("$set", new Document(BaseInfoSo.MODIFY_TIME,now));
collection.findOneAndUpdate(filter, doc, new FindOneAndUpdateOptions().upsert(false));

但是又不想把金额作为查询条件,期间很可能有变动的。
经查询发现mongodb从3.4版本开始支持 decimal128 类型,
具体参考https://en.wikipedia.org/wiki/Decimal128_floating-point_format
mongodb字段类型可存为Decimal28类型,上面的更新可改为


            Bson filter = Filters.eq(BaseInfoSo.CONT_ID,dto.getContId());
            Document doc = new Document("$inc", new Document(BaseInfoSo.CALL_TIMES, 1)
                    .append(BaseInfoSo.BALANCE, new Decimal128(BigDecimal.valueOf(-dto.getExpense()));
            collection.findOneAndUpdate(filter, doc, new FindOneAndUpdateOptions().upsert(false));
        

但是java double 和 mongodb decimal128之间并不能直接转换,这就需要我们自己做转换了
在java > mongodb:

向mongodb中插入java bean dto:

            Document doc2 = Document.parse(GsonUtil.getInstance().toJson(dto));
            System.out.println("转换前:"+doc2);
            Document appendDoc = new Document();
             Iterator<Entry<String, Object>> it = doc2.entrySet().iterator();
             while(it.hasNext()){
                 Entry<String, Object> e = it.next();
                    String key = e.getKey();
                    Object value = e.getValue();
                    if(value instanceof Double){
                        it.remove();
                        System.out.println(key+" is double type");
                        appendDoc.append(key,  new Decimal128(BigDecimal.valueOf((Double)value)));
                    }
             }
            doc2.putAll(appendDoc);
            System.out.println("转换后:"+doc2);
            collection.insertOne(doc2);

mongodb>java

        Document doc = cur.next();
        Document appendDoc = new Document();
         Iterator<Entry<String, Object>> it = doc.entrySet().iterator();
         while(it.hasNext()){
             Entry<String, Object> e = it.next();
                String key = e.getKey();
                Object value = e.getValue();
                if(value instanceof Decimal128){
                    it.remove();
                    System.out.println(key+" in mongodb is Decimal128 type");
                    appendDoc.append(key,  ((Decimal128) value).bigDecimalValue().doubleValue());
                }
         }
         doc.putAll(appendDoc);

再直接用json工具直接反序列化成java 对象就可以了。

 JAVADto dto = GsonUtil.getInstance().fromJson(doc.toJson(), JAVADto.class);

后续

后面发现不用这么麻烦的解析,我们可以自己修改document 的解析器

《mongodb double 精度解决方案》 image.png

String json = MongoDoc2JsonUtils.toJson(doc);
这样就只有数字了

    原文作者:Josen_Qu
    原文地址: https://www.jianshu.com/p/69d247170a75
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞