Franz
Franz

Reputation: 29

Manual Referencing vs. DBRef in Spring Data MongoDB?

I'm still learning MongoDB and it's drivers, so forgive my ignorance.

I understand that Spring Data MongoDB can automatically map something like this:

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

It populates my POJO's perfectly, in nested collections. However I tried manual referencing as well, something like this:

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

And this is the error I received

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

In the docs for Manual Reference it says

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

Now I understand that they literally mean you yourself have to go in and join these in code. Now for DBRef, they have this

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

My question: Is the reason many drivers (like Spring Data MongoDB) resolve DBRefs for you because they are scoped to a single collection? And there's no such thing as manual reference auto-resolution because they would have to scan the whole database instead?

And a follow up, my models contains a finite set of many-to-many relationships which also have a lot of repeated data, so I don't want to embed. Image if the parent-child in the object-array are flipped, need that use case.

So would my choices be

  1. Write a custom type convertor for manual referencing in Spring Data MongoDB (is that even a thing?)
  2. Use DBRefs for all items in a collection
  3. Have a separate relation table that links IDs and query them using $lookup (How does performance compare to DBRef?)
  4. Don't use MongoDB for lots of many-to-many use cases? Maybe this is the wrong tool for that and I should stick with RDBMS databases?

Thank you very much in advance.

Upvotes: 1

Views: 1361

Answers (1)

kieguer
kieguer

Reputation: 11

take a look at relmongo framework which allows you to implement relationships using annotations.

Upvotes: 1

Related Questions