javamongodbspring-webfluxspring-data-mongodbspring-data-mongodb-reactive

Map one mongodb field to two POJO properties


I have a property on my mongodb entity, lets call it foo.

When I retrieve this property, i want its value to be set on two different properties of my POJO, foo and bar

So if a document is registered as:

{
  "_id": "xxxxxx",
  "foo": "123",
}

When the service retrieves it from the DB, i want the fetched entity to look like this:

{
  "_id": "xxxxxx",
  "foo": "123",
  "bar": "123",
}

Is there a way to achieve this only changing the entity class? I tried the following and it didn't work

@Getter
@Setter
@Document("test")
public class MyClass {
    @Id
    private String _id;

    @BsonProperty("foo")
    private String bar;

    private String foo;

}

I'm using Spring Webflux and Reactive MongoDB stack.


Solution

  • It's not allowed to map multiple object fields to a single db field but you can redefine getter for the bar

    @Getter
    @Setter
    @Document("test")
    public class MyClass {
        @Id
        private String _id;
    
        @BsonProperty("foo")
        private String foo;
    
        private String bar;
    
        public String getBar() { 
           return foo; 
        }
    
    }