V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
JhOOOn
V2EX  ›  问与答

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

  •  
  •   JhOOOn · 2016-03-03 20:18:00 +08:00 · 5929 次点击
    这是一个创建于 3214 天前的主题,其中的信息可能已经有所发展或是发生改变。

    菜鸟一枚,使用 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 存储有什么好处吗?

    5 条回复    2016-03-04 08:59:27 +08:00
    typcn
        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
    klausgao
        2
    klausgao  
       2016-03-03 22:43:43 +08:00 via iPhone
    作用是,如果你用 mongoose 的话,可以用 populate 展开那个对象
    qinix
        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 的时候都一定会产生额外的查询
    JhOOOn
        4
    JhOOOn  
    OP
       2016-03-04 08:58:38 +08:00
    @qinix 谢谢您的回答
    JhOOOn
        5
    JhOOOn  
    OP
       2016-03-04 08:59:27 +08:00
    @typcn 谢谢您的教训,下回一定会使用工具前先通读文档。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1245 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 23:59 · PVG 07:59 · LAX 15:59 · JFK 18:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.