【问题标题】:is there a method to query list of unique B Object inside object A from MongoDb using Spring boot有没有一种方法可以使用 Spring boot 从 MongoDb 中查询对象 A 内的唯一 B 对象列表
【发布时间】:2020-11-28 19:12:47
【问题描述】:

我们有

class A{

@id
int id;

List <B> bs;

}

在哪里

class B{

 String prId;

 int pr;

}

我需要一种使用 prId 获取 B 列表而不重复的方法。 所以请建议一种获取方式

[
{
prId: "18876",
pr: 1228876
},
{
prId: "123",
pr: 1228876
}
]

【问题讨论】:

    标签: mongodb list spring-boot nosql


    【解决方案1】:

    2 个解决方案(或更多)

    1. List&lt;B&gt; bs; 更改为 Set&lt;B&gt; bs; 并确保 B 类具有仅基于 prId 的 equal/hashcode 方法

    2. 由于 B 是文档的嵌入列表(B 没有它的集合),因此在保存 A 时没有创建 id,您可以像这样在保存 A 时自己生成一个 mongo id (ObjectId)

    class B{
     @Id
     String prId;
     int pr;
     // get set
    }
    B b = new B();
    b.setPrId(ObjectId.get().toString());
    

    然后通过检索 A,所有 B 都应该是唯一的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      相关资源
      最近更新 更多