Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - is DBREF necessary?

Tags:

mongodb

dbref

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 }     ] ], 
like image 692
Industrial Avatar asked Feb 23 '12 11:02

Industrial


People also ask

Should I use Dbref?

Basically, I would say that you should only use those DBrefs if the linked document can be of variable type. If it's static then you're stuck with _id-references and maybe your own lazy loader functionality, so you don't repeat yourself.

What is the use of @dbref?

DBRefs are references from one document to another using the value of the first document's _id field, collection name, and, optionally, its database name, as well as any other fields. DBRefs allow you to more easily reference documents stored in multiple collections or databases.

Is there foreign key in MongoDB?

MongoDB ReferencesNormally, MongoDB doesn't work with the concept of foreign keys. The foreign keys can be used in the Relational Databases for visualizing data from multiple collections simultaneously.

What is $ref in MongoDB?

The $ref field holds the name of the collection where the referenced document resides. $id. The $id field contains the value of the _id field in the referenced document. $db.


1 Answers

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.

like image 142
Andrew Orsich Avatar answered Sep 22 '22 20:09

Andrew Orsich