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.

2
  • did you try animalRepo.findAll. By default it returns onlty the fields you have mapped in Entity class. Commented Jul 26, 2018 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. Commented Jul 27, 2018 at 6:14

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

5 Comments

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.
Firstly, sorry for the typo, I edited it. Maybe this can help stackoverflow.com/questions/10421966/…
@SandeepMR ya, you should use a discriminator field in every document and whey you do repo.findAllByDescrimator("human")
@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 its Custom repo method findAllBy<your_field_name>(String fieldName) it will fetch all those records which are matching with your_field

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.