Home > Net >  How do I fetch specific types inheriting from an abstract class from spring-mongodb with one query?
How do I fetch specific types inheriting from an abstract class from spring-mongodb with one query?

Time:06-28

I'm using Spring MongoDb Data, and I have two classes A and B inheriting from class C. Both A and B has the '_class' field. I want to fetch a list of documents with both A and B in them, and have them be mapped to their inheriting objects, but using MongoOperation it seems that it's only possible to put one class entity with each query. Is there a way to fetch a list of both A and B and have them polymorphed to their corresponding java objects? Or fetching the abstract C is the only way to fetch both A and B at the same time?

CodePudding user response:

The single type parameter you hand into the ….find…(…) methods of MongoTemplate is effectively a shortcut to define both the collection to be read and the types of objects to be produced eventually by the document mapping subsystem. It does not restrict the document selection in any way. This effectively implements a type-hierarchy-by-collection approach.

If you want to restrict the query result to only some subtypes, you need to use the Query type's ….restrict(Class, Class…) method that allows to define which nominal types are supposed to be read. That effectively translates in to a constraint against the type aliases being persisted on write, as MongoDB documents don't know anything about types on the client in the first place.

  • Related