Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB type inference using _class

I've been reading the MongoDB documentation and Spring adds a _class field by default to the stored data. Is there any way to use this information to have type inference?

For example: There is a an abstract class Animal with three subclasses Dog, Cat, Bird. Say you have a class Zoo which contains a list of animals. In the database you store those Zoo Objects. Is there any function to get a List<Animal> back with Animals that can be upcasted?

I'm using Spring so I prefer to have a solution that would work using the spring-data-mongodb. But an external mapping library would be fine too. I prefer not to write it myself as it seems basic mapping functionality.

like image 216
Vjeetje Avatar asked Oct 04 '22 02:10

Vjeetje


1 Answers

Make sure you map all types you mentioned to be stored in the same collection (e.g. using the @Document annotation). Then you can simply execute queries against the collection handing in Animal to the according method on MongoTemplate. The underlying converter will then automatically instantiate the correct types based on the information stored in _class. The same applies to the usage of Spring Data MongoDB repositories.

like image 140
Oliver Drotbohm Avatar answered Oct 05 '22 17:10

Oliver Drotbohm