How to create Decimal128 field with inc operator in java/scala

笑着哭i 提交于 2020-01-04 05:40:08

问题


I have following document structure:

{
    "moneys": {
      "someKey": NumberDecimal(99)
      ...
      "someOtherRandomKey": NumberDecimal(99)
    }
{

What I want: When nonexistent field increments, create that field with NumberDecimal value.

I tried it with scala driver but cant do that:

//not compiles
collection.findOneAndUpdate(filters,Updates.inc("someOtherKey", new Decimal128(50)))

because Updates.inc(k,v) requires Number; Decimal128 is not Number

I think problem not in driver, but with my logic.

How can I implement my case with scala/java driver?


回答1:


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()
  }
}

Register in mongo:

 val codecRegistry = fromRegistries(fromCodecs(new BigDecimalScalaCodec()), DEFAULT_CODEC_REGISTRY)

 val database: MongoDatabase = mongoClient.getDatabase("dbName")
    .withCodecRegistry(codecRegistry)

And now we can use scala.math.BigDecimal:

collection.findOneAndUpdate(filters,Updates.inc("someOtherKey", BigDecimal(99))


来源:https://stackoverflow.com/questions/45053457/how-to-create-decimal128-field-with-inc-operator-in-java-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!