Spring Data MongoDB中的手动引用与DBRef?

时间:2019-05-10 13:48:23

标签: mongodb nosql spring-data-mongodb

我仍在学习MongoDB及其驱动程序,请原谅我的无知。

我了解到Spring Data MongoDB可以自动映射如下内容:

{
  "_id" : ObjectId("5cd4e8140615c7480f549907"),
  "name" : "test",
  "otherCollection" : [ 
    {
      "$ref" : "otherCollection",
      "$id" : ObjectId("5cd4e8140615c7480f549905")
    }
  ]
}

它完美地填充了嵌套集合中的POJO。但是我也尝试了手动引用,如下所示:

{
  "_id" : ObjectId("5cd4e8140615c7480f549906"),
  "name" : "test",
  "otherCollection" : [ 
    ObjectId("5cd4e8140615c7480f549905")
  ]
}

这是我收到的错误

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.bson.types.ObjectId] to type [com.test.test.model.OtherObject]

在《手册参考》文档中说

Then your application can run a second query to return the related data.

现在,我了解到它们从字面上意味着您自己必须加入并将它们加入代码中。现在,对于DBRef,他们有这个

Some community supported drivers may have alternate behavior and may resolve a DBRef into a document automatically.

我的问题:许多驱动程序(例如Spring Data MongoDB)之所以为您解析DBRef是因为它们的作用域是单个集合吗?而且没有手动参考自动解析这样的事情,因为他们将不得不扫描整个数据库?

随后,我的模型包含一组有限的多对多关系,这些关系也包含大量重复数据,因此我不想嵌入。如果对象数组中的父子对象被翻转,则需要该用例。

所以我的选择会是

  1. 编写一个自定义类型转换器以在Spring Data MongoDB中进行手动引用(甚至可以吗?)
  2. 对集合中的所有项目使用DBRefs
  3. 具有一个单独的关系表,该关系表链接ID并使用$lookup查询ID(与DBRef相比,性能如何?)
  4. 不要将MongoDB用于许多多对多用例吗?也许这是错误的工具,我应该坚持使用RDBMS数据库?

非常感谢您。

1 个答案:

答案 0 :(得分:1)

看看 relmongo 框架,该框架使您可以使用注释来实现关系。

相关问题