mongodb 的引用 DBRef 和直接保存_id 的区别?

2016-03-03 20:18:00 +08:00
 JhOOOn

菜鸟一枚,使用 mongodb 存储数据,有两个文档 courses, student :

courses 集合:
  x = { "name" : "Biology" }
student 集合:
DBRef:
stu1 = { name : 'Joe', classes : [ new DBRef('courses', x._id) ] }

直接存_id:

stu2 = { name : 'Joe', classes : [ x._id ] }

比如通过 student 查询 courses 都需要查询两次, 请问使用 DBRef 存储有什么好处吗?

5934 次点击
所在节点    问与答
5 条回复
typcn
2016-03-03 20:41:37 +08:00
https://docs.mongodb.org/manual/reference/database-references/

"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. By including these names, DBRefs allow documents located in multiple collections to be more easily linked with documents from a single collection.
To resolve DBRefs, your application must perform additional queries to return the referenced documents. Many drivers have helper methods that form the query for the DBRef automatically. The drivers [1] do not automatically resolve DBRefs into documents.
DBRefs provide a common format and type to represent relationships among documents. The DBRef format also provides common semantics for representing links between documents if your database must interact with multiple frameworks and tools."

RTFM before u ask
klausgao
2016-03-03 22:43:43 +08:00
作用是,如果你用 mongoose 的话,可以用 populate 展开那个对象
qinix
2016-03-03 23:38:47 +08:00
@typcn 你引用的这一段并没有回答楼主的问题,直接保存 _id 也能实现上述功能,并且在 MongoDB 官方文档中明确说了大部分时候应该用直接保存 _id 的方法而不是 DBRef

> In most cases you should use the manual reference method for connecting two or more related documents. However, if you need to reference documents from multiple collections, consider using DBRefs.

参见网址: https://docs.mongodb.org/manual/reference/database-references/#id4

并且网上大部分专业回答也都是建议避免使用 DBRef ,如: http://stackoverflow.com/questions/9412341/mongodb-is-dbref-necessary 因为所有的驱动在遇到 DBRef 的时候都一定会产生额外的查询
JhOOOn
2016-03-04 08:58:38 +08:00
@qinix 谢谢您的回答
JhOOOn
2016-03-04 08:59:27 +08:00
@typcn 谢谢您的教训,下回一定会使用工具前先通读文档。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/260912

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX