By default when using spring-data-mongodb, Spring uses a MappingMongoConverter
to convert domain objects to | from document.
The default converter policy for id property is as follows:
The following outlines what field will be mapped to the '_id' document field:
A field annotated with @Id (org.springframework.data.annotation.Id) will be mapped to the '_id' field. A field without an annotation but named id will be mapped to the '_id' field. The following outlines what type conversion, if any, will be done on the property mapped to the _id document field.
If a field named 'id' is declared as a String or BigInteger in the Java class it will be converted to and stored as an ObjectId if possible. ObjectId as a field type is also valid.
This conversion is not done by default to any other standard property. So if you want userID
field to be saved as ObjectId
simply change the field type: private ObjectId userID;
Not that the oposite case is less simple if you want to save the id
property of User
as String in MongoDB, you will have to supply your own mapping converter which overrides the writeInternal
method (by it's name it implies you shouldn't) or override some other Spring MongoDB plumbing bean further down the conversion process