V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
JhOOOn
V2EX  ›  问与答

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

  •  
  •   JhOOOn · Mar 3, 2016 · 6420 views
    This topic created in 3720 days ago, the information mentioned may be changed or developed.

    菜鸟一枚,使用 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 replies    2016-03-04 08:59:27 +08:00
    typcn
        1
    typcn  
       Mar 3, 2016
    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  
       Mar 3, 2016 via iPhone
    作用是,如果你用 mongoose 的话,可以用 populate 展开那个对象
    qinix
        3
    qinix  
       Mar 3, 2016   ❤️ 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
       Mar 4, 2016
    @qinix 谢谢您的回答
    JhOOOn
        5
    JhOOOn  
    OP
       Mar 4, 2016
    @typcn 谢谢您的教训,下回一定会使用工具前先通读文档。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   872 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 136ms · UTC 21:39 · PVG 05:39 · LAX 14:39 · JFK 17:39
    ♥ Do have faith in what you're doing.