MongoDB - DBREF 是必要的吗?
在 MongoDB 中使用 DBREF 数据类型,文档可能如下所示如下所示。但是在每一行中都有 $ref
字段感觉是多余的,因为每一行显然都指向 users
集合。
有没有一种方法可以引用其他文档而没有多余的 $ref
字段?
{
$id: {$oid : "4f4603820e25f4c515000001"},
title: "User group",
users: [
{_id: {$ref: "users", $id: { $oid: "4f44af6a024342300e000002"}}, isAdmin: true }
]
],
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 }
]
],
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为在使用 mongodb 时应该避免使用 Dbref,至少如果您使用需要可扩展性的大型系统。
据我所知,所有驱动程序都会发出额外的请求来加载 DBRef,因此它不是数据库内的“加入”,它非常昂贵。
是的,牢记引用,为“外键”创建命名约定(例如 RefUserId 或只是 UserId)并仅存储引用文档的 ID。需要时自行加载参考文档。还要密切关注您可以执行的任何非规范化、嵌入,因为它通常会极大地提高性能。
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.
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.
除非您使用特定于驱动程序的方法来访问
dbref
,否则应该没有必要。如果您手动管理连接(即您知道要“连接”到哪个其他集合),则仅存储 ObjectId 就足够了。
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.
来自 文档:
手动引用 是一种替代方案,文档说手动引用优于 DBREF(虽然我不确定为什么)。
当引用的对象位于另一个数据库中或者集合名称不明显时,DBREF 会很有帮助。
非规范化/嵌入优于任何类型的链接,因为这样您就可以获得原子更新并且不需要重新查询相关数据。
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.