4

Coming from a RDMBS background it's hard not to think of thinkgs like joins, especially when working with the schema-less MongoDB environemnt.

I read on a blog that DBRefs were only useful when you do know the type of object that you're referencing.

Why is this so? Surely they have more use than that.

Say I have a user collection, and an employer collection. Many users can reference the same employer. To me, this is the perfect use of a DBRef. However, this contradicts what I read on that blog.

Sure, I could embed the employer into each user collection, but what happens when the employer changes? Maybe they employer changes address or phone number or something. If the employer is embedded in each user, then I'd have to update every user's embedded document.

That can't be efficient. Or can it?

Community
  • 1
  • 1
  • 4
    Have you read [this](http://www.mongodb.org/display/DOCS/Database+References)? You seem to have missed the third, most common option, which is to simply store the id of another document in a field and manage the reference manually :-) – Cameron Aug 07 '11 at 21:47
  • 1
    Do note however that the author's claim "[DBRefs] because they are supported by Mongo" is not strictly true. It's a convention put in place that drivers can use to perform lazy fetching of DBRef'd fields but there is no server-side support for it. It's convention and it's up to drivers to support it (most do). – Remon van Vliet Aug 08 '11 at 07:33

1 Answers1

10

DBRefs is a data structure which include a collection name and an object id. If you know the name of you collection (like in your example, employer), you don't need a DBRef. Just store the object id of the employer in your user collection. You save the space taken by the collection name.

Use DBRef when the collection name can change. For example, you have a comment collection. You want to use it to store comments on blog post and on book pages (2 differents collections). If you want to store a reference to the post or the page in your comment, you need to use a database reference.

Maxence
  • 12,868
  • 5
  • 57
  • 69