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 } ] ],
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With