如何使用Java检索具有大于某个值的BigDecimal值的MongoDB记录

huangapple 未分类评论42阅读模式
英文:

How to fetch mongo db records having BigDecimal value greater than a value using java

问题

我无法获取MongoDB中金额(bigdecimal 值)大于0的记录,使用以下Java代码:

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

I am unable to fetch mongo db records having amount (bigdecimal value) greater than 0 using following in java.

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

答案1

得分: 0

  • 看起来首先你需要将现有的 MongoDB 文档转换为 Decimal128 进行存储。
   db.xxx.find({ }) 
  .forEach( function (x) { 
    x.price = new NumberDecimal(x.amount); 
    db.xxx.save(x); 
  });
  • 然后你需要编写一个 Converter
    @Bean
    CustomConversions customConversions() {
     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));
    }
英文:
  • It looks like first you have to convert the existing documents mongodb to store it as Decimal128
   db.xxx.find({ }) 
  .forEach( function (x) { 
    x.price = new NumberDecimal(x.amount); 
    db.xxx.save(x); 
  });
  • Then you need to write a Converter
    @Bean
    CustomConversions customConverions() {
     Converter&lt;Decimal128, BigDecimal&gt; decimal128ToBigDecimal 
                    = new Converter&lt;Decimal128, BigDecimal&gt;() {
        @Override
        public BigDecimal convert(Decimal128 s) {
            return s==null ? null : s.bigDecimalValue();
        }
      };

      Converter&lt;BigDecimal, Decimal128&gt; bigDecimalToDecimal128 
                    = new Converter&lt;BigDecimal, Decimal128&gt;() {
        @Override
        public Decimal128 convert(BigDecimal s) {
            return s==null ? null : new Decimal128(s);
        }
      };

      return new CustomConversions(Arrays.asList(decimal128ToBigDecimal, 
                                 bigDecimalToDecimal128));
    }

huangapple
  • 本文由 发表于 2020年7月26日 01:29:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/63091387.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定