Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does spring data mongodb supports manual referencing or it supports only DBrefs?

I am using spring data mongodb and want to use manual referencing in my application and resolve them on need basis. I read spring data mongodb documentation but couldn't find if spring supports manual references? It supports DBRefs and resolve them eagerly which I don't want. Does anyone know how to use manual references with spring data or if it is supported by it at all? I am asking this because mongodb docs recommend this and it suits most of the use cases.

like image 216
xabhi Avatar asked May 01 '14 14:05

xabhi


1 Answers

It depends on what you mean by 'supporting' it. The mongo docs actually recommend using manual references rather than using DBRefs. All a DBRef does is store the collection name and a document id. It optionally stores the db name if multiple db's are in use and you are referring to something in another one.

The nice thing about DBRefs is that the referred document is automatically fetched with you load the document containing the DBRef. The pain with DBRefs is that the referred doc is ALWAYS loaded because it is a greedy load.

If you know where documents are going to be stored, it is often easier and more efficient to simply store the referred document's id in a field and load the referenced document yourself rather than using a DBRef.

How you use manual references all depends on how you want them to work, and your question doesn't quite specify that much detail.

{
  "_id" : [some id],
  "refId" : [some other id]
}

Update:

Just noticed that Spring Data has finally implemented lazy loading of DBRefs, so you can use the annotation @DBRef(lazy = true) and the ref is loaded on demand. The main reason not to use DBRefs has been removed, so you need to decide if the additional work of doing manual references is worth it

Update #2

Having worked with DBRefs for a while, I actually wish I had not used them. They don't play well with aggregations and trying to do queries and updates with them via shells and such is typically a pain. I will say that the MongoDB recommendation of doing manual references rather than using DBRef's if your use case is simple enough is my recommendation as well.

like image 97
DavidA Avatar answered Oct 23 '22 02:10

DavidA