【问题标题】:How to fetch mongo db records having BigDecimal value greater than a value using java如何使用java获取BigDecimal值大于值的mongo db记录
【发布时间】:2020-07-25 17:29:09
【问题描述】:

我无法在 java 中使用以下方法获取数量(bigdecimal 值)大于 0 的 mongo db 记录。

    Query query=new Query();
    query.addCriteria(Criteria.where("amount").gt(0));

【问题讨论】:

    标签: java mongodb spring-boot


    【解决方案1】:
    • 看起来首先你必须将现有文档转换为 mongodb 以将其存储为Decimal128
       db.xxx.find({ }) 
      .forEach( function (x) { 
        x.price = new NumberDecimal(x.amount); 
        db.xxx.save(x); 
      });
    
    • 那你需要写一个Converter
        @Bean
        CustomConversions customConverions() {
         Converter<Decimal128, BigDecimal> decimal128ToBigDecimal 
                        = new Converter<Decimal128, BigDecimal>() {
            @Override
            public BigDecimal convert(Decimal128 s) {
                return s==null ? null : s.bigDecimalValue();
            }
          };
    
          Converter<BigDecimal, Decimal128> bigDecimalToDecimal128 
                        = new Converter<BigDecimal, Decimal128>() {
            @Override
            public Decimal128 convert(BigDecimal s) {
                return s==null ? null : new Decimal128(s);
            }
          };
    
          return new CustomConversions(Arrays.asList(decimal128ToBigDecimal, 
                                     bigDecimalToDecimal128));
        }
    

    【讨论】:

    • 我无法更改现有字段的数据类型。在文档中它总是 BigDecimal。请提出一种方法,这样我就可以在不修改现有数据库的情况下获取结果。
    • 不幸的是,当它存储为字符串时,您将无法在 mongo 中进行比较
    猜你喜欢
    • 2012-01-29
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 2021-03-21
    • 2014-09-24
    • 2021-05-24
    相关资源
    最近更新 更多