MongoDB - 是否需要 DBREF?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9412341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB - is DBREF necessary?
提问by Industrial
Using the DBREF datatypein 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.
使用MongoDB 中的DBREF 数据类型,文档可能如下所示。但是$ref
每一行都有这个字段感觉是多余的,因为每一行显然都指向users
集合。
Is there a way to reference other documents without having the somewhat redundant $ref
-field?
有没有办法在没有有点冗余的$ref
字段的情况下引用其他文档?
{
$id: {$oid : "4f4603820e25f4c515000001"},
title: "User group",
users: [
{_id: {$ref: "users", $id: { $oid: "4f44af6a024342300e000002"}}, isAdmin: true }
]
],
回答by Andrew Orsich
Dbref in my opinion should be avoided when work with mongodb, at least if you work with big systems that require scalability.
我认为在使用 mongodb 时应该避免使用 Dbref,至少如果您使用需要可扩展性的大型系统。
As i know all drivers make additional request to load DBRef, so it's not 'join' within database, it is very expensive.
我知道所有驱动程序都会额外请求加载 DBRef,所以它不是数据库中的“加入”,它非常昂贵。
Is there a way to reference other documents without having the somewhat redundant $ref-field?
有没有办法在没有有点多余的 $ref 字段的情况下引用其他文档?
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.
是的,记住引用,为“外键”创建命名约定(类似于 RefUserId 或只是 UserId)并仅存储引用文档的 id。需要时自行加载参考文档。还要留意任何非规范化,嵌入你可以做的,因为它通常会大大提高性能。
回答by zulkamal
Unless you use driver specific methods for accessing dbref
, it should be unnecessary.
除非您使用驱动程序特定的方法来访问dbref
,否则应该没有必要。
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.
在您手动管理连接的情况下(即您知道要“连接”到哪个其他集合),仅存储 ObjectId 就足够了。
回答by Max Heiber
From the docs:
从文档:
Manual referencesare an alternative, and the docs saymanual 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.
手动引用是一种替代方法,文档说手动引用比 DBREF 更可取(尽管我不确定为什么)。当引用的对象位于另一个数据库中或集合名称不明显时,DBREF 很有用。
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.
非规范化/嵌入比任何类型的链接都更可取,因为这样您可以获得原子更新并且不需要重新查询相关数据。