菜鸟一枚,使用 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 存储有什么好处吗?
1
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 |
2
klausgao 2016-03-03 22:43:43 +08:00 via iPhone
作用是,如果你用 mongoose 的话,可以用 populate 展开那个对象
|
3
qinix 2016-03-03 23:38:47 +08:00 1
@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 的时候都一定会产生额外的查询 |