Java POJO mapping to mongo document with sub documents

Hello, I would like to check if anyone has used mongo document field mapping to pojo using @Field spring annotation? Also, did anyone use a specific convention of mapping instead of property to field, using more detailed explicit mapping to a sub document field to a property. say:
"{Person: {Address: City}} mapping city to pojo property as “person.address.city” instead of creating multiple embedded POJO for person, address.

Please advice.

Hello @Gopal_P_Muthyala, welcome to the MongoDB community forum.

I would like to check if anyone has used mongo document field mapping to pojo using @Field spring annotation?

The @Field annotation is to define custom metadata for document fields. This annotation is applied at the field level. It lets describe the name and type of the field as it will be represented in the MongoDB BSON document. This allows the name and type to be different than the field name of the class as well as the property type.

For example a MongoDB collection’s document has a field with name fname and the Pojo class mapped to it can define the property as:

@Field("fname")
private String firstName;

And, the mapping of the Java types to BSON types using the targetType attribute with values as defined in FieldType.

@Field(targetType = DECIMAL128)
private BigDecimal amount;

If a field mapping needs no customization, then there is no need to use this annotation.


Also, did anyone use a specific convention of mapping instead of property to field, using more detailed explicit mapping to a sub document field to a property. say:
"{Person: {Address: City}} mapping city to pojo property as “person.address.city” instead of creating multiple embedded POJO for person, address.

If a Person class has a Address property, and if this is mapped to a MongoDB document in a person collection, then the document will be as:
{ _id: <ObjectId>, personName: <string>, address: { number: <int>, street: <string>, city: <string> } }

The Person.java and Address.java Pojo classes are defined for this mapping (sometimes, Address class can be a static inner class within the Person class).

To simplify the coding in the Pojo classes, you can use the Project Lombok utility lbrary - this lets you annotate properties and not write their get/set, toString, hashcode and equals method code. There are quite a few annotations in this library including @Getter/Setter, @ToString, etc.

1 Like

Thank you Prasad, Sure i will look at the Project Lombok. So to map city in a Person POJO, do i need to have Person, and Address pojo? Since my use case has a lot of pojo and complex nested mongo document. I just want one Pojo with all details as in PersonAddress.java having city as a property with @Field (“person.address.city”), would that work?

I don’t know. Did you try? What did you find?