MongoDB type inference using _class

I read the MongoDB documentation and Spring adds the _class field to the default saved data. Is there any way to use this information for type inference?

For example: there is an abstract class Animal with three subclasses Dog, Cat, Bird. Say you have a cool zoo that contains a list of animals. In the database, you store these Zoo objects. Is there any function to get the List<Animal> back with animals that can be increased?

I use Spring , so I prefer to have a solution that will work using spring-data-mongodb . But an external mapping library will be wonderful too. I prefer not to write it myself, as it looks like a basic display function.

+4
source share
1 answer

Make sure you map all the types you mentioned to be stored in the same collection (for example, using the @Document annotation). Then you can simply execute the requests against passing the collection to Animal according to the MongoTemplate method. Then, the base converter will automatically create the correct types based on the information stored in _class. The same goes for using Spring Data MongoDB repositories.

+3
source

Source: https://habr.com/ru/post/1499468/


All Articles