1

I am in a situation where I have to store data belonging to multiple entities in a single collection. But when I query then back, I dont want unwanted records in my result. How can we achieve this using spring? Below is what I have done so far.

1. I give same collection name in entity as shown below.

@Document(collection = "livingThings")
@Data
public class AnimalEntity {
    //contains id, type, bla, bla
}

@Document(collection = "livingThings")
@Data
public class HumanEntity {
  //contains id, gender, address
}

2. I create independent mongoRepository interfaces

public interface AnimalRepository implements MongoRepository<AnimalEntity, String> {

}

public interface HumanRepository implements MongoRepository<HumanEntity, String> {

}

3. And the problem is

when I do animalRepo.findAll or humanRepo.findAll, I get all records available in the collection.

4. What I expect

animalRepo.findAll returns only those records where document structure is same as AnimalEntity.

Thank you very much for your time and patience to attend this query.

Sandeep M R
  • 25
  • 1
  • 6
  • did you try animalRepo.findAll. By default it returns onlty the fields you have mapped in Entity class. – pvpkiran Jul 26 '18 at 14:49
  • Yes I tried it. It has not worked yet. I am trying to figure out if it needs any additional configuration to behave in the way you mentioned. – Sandeep M R Jul 27 '18 at 06:14

1 Answers1

2

MongoDB automatically adds _class field to entities in a collection. Even though it is not the best solution, you can try this:

@Query("_class:your package name here.AnimalEntity")
public AnimalEntity findAllAnimals();
Onur Arı
  • 502
  • 1
  • 4
  • 16
  • You are right about the _class. And I am expecting that there must be a way to tell all queries to match this class for the entity type defined in the interface implementation. If I have to write it explicitly using @Query, that would be an overhead for future maintenance and development. – Sandeep M R Jul 27 '18 at 06:18
  • Firstly, sorry for the typo, I edited it. Maybe this can help https://stackoverflow.com/questions/10421966/spring-data-mongodb-querying-multiple-classes-stored-in-the-same-collection?rq=1 – Onur Arı Jul 27 '18 at 06:31
  • @SandeepMR ya, you should use a discriminator field in every document and whey you do `repo.findAllByDescrimator("human")` – Rookie007 Aug 12 '21 at 12:08
  • @Rookie007 - it would have been very helpful if you included more in your example. What does the interface look like? Is it capitalization sensitive? – barrypicker Oct 19 '21 at 20:30
  • @barrypicker its Custom repo method `findAllBy(String fieldName)` it will fetch all those records which are matching with `your_field` – Rookie007 Oct 20 '21 at 10:03