MongoDB
 SQL >> Base de Dados >  >> NoSQL >> MongoDB

Filtrando YearMonth em documento Mongo

Você precisará criar um codec customizado para Year Month, pois isso não é um tipo Bson padrão. Isso envolve duas etapas. Ajuste conforme suas necessidades.

Crie o codec

public class YearMonthCodec implements Codec<YearMonth> {
    public void encode(BsonWriter writer, YearMonth value, EncoderContext encoderContext) {
        writer.writeStartDocument();
        writer.writeName("year");
        writer.writeInt32(value.getYear());
        writer.writeName("month");
        writer.writeInt32(value.getMonth().getValue());
        writer.writeEndDocument();
    }

    public Class<YearMonth> getEncoderClass() {
        return YearMonth.class;
    }

    public YearMonth decode(BsonReader reader, DecoderContext decoderContext) {
        reader.readStartDocument();
        int year = reader.readInt32("year");
        int month = reader.readInt32("month");
        reader.readEndDocument();
        return YearMonth.of(year, month);
    }
}

Registre o codec com o cliente Mongo

CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
    CodecRegistries.fromCodecs(new YearMonthCodec()),
    MongoClient.getDefaultCodecRegistry()
);
MongoClientOptions options = MongoClientOptions.builder()
    .codecRegistry(codecRegistry)
    .build();
MongoClient mongoClient = new MongoClient(new ServerAddress(), options);