如何在spring-data-mongodb框架中将BigDecimal转换为Double

Spring Data MongoDB映射默认情况下将BigDecimal转换为String。 但是,我希望它们在mongodb中转换为Double。 这是后者在mongodb(比较查询/聚合查询)中对此字段进行查询所必需的。 我如何重新编译自己的转换器(BigDecimalToDouble / DoubleToBigDecimal)来执行此操作?

以下是添加自己的转换器的方法:

             

现在你的转换器看起来像:

 @Component public class DoubleToBigDecimalConverter implements Converter { @Override public BigDecimal convert(Double source) { return new BigDecimal(source); } } @Component public class BigDecimalToDoubleConverter implements Converter { @Override public Double convert(BigDecimal source) { return source.doubleValue(); } } 

在添加转换器之前我得到:

 update test.product query: { _id: 123 } update: { _id: 123, _class: "com.vladmihalcea.mongo.model.Product", name: "Tv", quantity: "10", discount: "12.34", version: 0 } nscanned:0 nupdated:1 upsert:1 keyUpdates:0 locks(micros) w:49328 50ms 

添加转换器后:

 update test.product query: { _id: 123 } update: { _id: 123, _class: "com.vladmihalcea.mongo.model.Product", name: "Tv", quantity: "10", discount: 12.34, version: 0 } nscanned:0 nupdated:1 upsert:1 keyUpdates:0 locks(micros) w:64689 65ms