简体   繁体   English

春季数据mongodb同一集合中的多个实体

[英]spring data mongodb multiple entity in same collection

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? 我们如何使用spring做到这一点? Below is what I have done so far. 以下是我到目前为止所做的事情。

1. I give same collection name in entity as shown below. 1.我在实体中给出了相同的集合名称,如下所示。

@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 2.我创建独立的mongoRepository接口

public interface AnimalRepository implements MongoRepository<AnimalEntity, String> {

}

public interface HumanRepository implements MongoRepository<HumanEntity, String> {

}

3. And the problem is 3.问题是

when I do animalRepo.findAll or humanRepo.findAll, I get all records available in the collection. 当我执行animalRepo.findAll或humanRepo.findAll时,我会获得集合中所有可用的记录。

4. What I expect 4.我的期望

animalRepo.findAll returns only those records where document structure is same as AnimalEntity. animalRepo.findAll仅返回文档结构与AnimalEntity相同的那些记录。

Thank you very much for your time and patience to attend this query. 非常感谢您的时间和耐心参加此查询。

MongoDB automatically adds _class field to entities in a collection. MongoDB自动将_class字段添加到集合中的实体。 Even though it is not the best solution, you can try this: 即使这不是最佳解决方案,也可以尝试以下操作:

@Query("_class:your package name here.AnimalEntity")
public AnimalEntity findAllAnimals();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM