Industrial
Industrial

Reputation: 42778

MongoDB - is DBREF necessary?

Using the DBREF datatype in MongoDB, a document may look like as shown below. But having the $ref field in every row feels redundant as every row obviously points to the users collection.

Is there a way to reference other documents without having the somewhat redundant $ref-field?

{
    $id: {$oid : "4f4603820e25f4c515000001"},
    title:   "User group",
    users: [ 
        {_id: {$ref: "users", $id: { $oid: "4f44af6a024342300e000002"}}, isAdmin: true }
    ]
],

Upvotes: 33

Views: 35073

Answers (3)

Max Heiber
Max Heiber

Reputation: 15502

From the docs:

Manual references are an alternative, and the docs say manual references are preferable to DBREFs (though I'm not sure why). DBREFs are helpful when the referenced object lives in another database or where the collection name would not otherwise be obvious.

Denormalization/embedding is preferable to any kind of linking because then you get atomic updates and don't need to re-query for the related data.

Upvotes: 5

Andrew Orsich
Andrew Orsich

Reputation: 53685

Dbref in my opinion should be avoided when work with mongodb, at least if you work with big systems that require scalability.

As i know all drivers make additional request to load DBRef, so it's not 'join' within database, it is very expensive.

Is there a way to reference other documents without having the somewhat redundant $ref-field?

Yes, keep references in the mind, create naming conventions for 'foreign keys' (something like RefUserId or just UserId) and store just id of referenced document. Load referenced documents yourself when needed. Also keep your eyes open for any denormalization, embedding you can do, because it's usually greatly improve performance.

Upvotes: 50

zulkamal
zulkamal

Reputation: 578

Unless you use driver specific methods for accessing dbref, it should be unnecessary.

In cases where you're managing the join manually (i.e. you know which other collection to "join" to), storing just the ObjectId is enough.

Upvotes: 6

Related Questions