如何在Java/scala中使用inc运算符创建Decimal128字段 [英] How to create Decimal128 field with inc operator in java/scala
本文介绍了如何在Java/scala中使用inc运算符创建Decimal128字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下文档结构:
{
"moneys": {
"someKey": NumberDecimal(99)
...
"someOtherRandomKey": NumberDecimal(99)
}
{
我想要的:当不存在的字段递增时,使用
NumberDecimal
值.
What I want: When nonexistent field increments, create that field with
NumberDecimal
value.
我使用scala驱动程序尝试了此操作,但无法做到这一点:
I tried it with scala driver but cant do that:
//not compiles
collection.findOneAndUpdate(filters,Updates.inc("someOtherKey", new Decimal128(50)))
因为Updates.inc(k,v)
需要Number
; Decimal128
不是Number
我认为问题不在于驱动程序,而在于我的逻辑.
I think problem not in driver, but with my logic.
如何使用scala/java驱动程序实现我的案例?
How can I implement my case with scala/java driver?
推荐答案
通过为scala.math.BigDecimal
实现编解码器解决的问题:
Problem solved by implementing codec for scala.math.BigDecimal
:
class BigDecimalScalaCodec extends Codec[scala.math.BigDecimal] {
override def encode(writer: BsonWriter, value: scala.math.BigDecimal, encoderContext: EncoderContext): Unit = {
writer.writeDecimal128(new Decimal128(value.bigDecimal))
}
override def getEncoderClass: Class[scala.math.BigDecimal] = classOf[scala.math.BigDecimal]
override def decode(reader: BsonReader, decoderContext: DecoderContext): scala.math.BigDecimal = {
reader.readDecimal128().bigDecimalValue()
}
}
注册mongo:
val codecRegistry = fromRegistries(fromCodecs(new BigDecimalScalaCodec()), DEFAULT_CODEC_REGISTRY)
val database: MongoDatabase = mongoClient.getDatabase("dbName")
.withCodecRegistry(codecRegistry)
现在我们可以使用scala.math.BigDecimal
:
collection.findOneAndUpdate(filters,Updates.inc("someOtherKey", BigDecimal(99))
这篇关于如何在Java/scala中使用inc运算符创建Decimal128字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文