dbref command in mongodb

情到浓时终转凉″ 提交于 2019-12-11 01:14:06

问题


I am newbie to mongodb. I need to do a query by reference two collections using dbref and need to query particular fields.

comments collection

        { 
          uid:12345, 
          pid:444, 
          comment="blah" 
        },

        { 
          uid:12345,
          pid:888, 
          comment="asdf" 
        },

        { 
          uid:99999, 
          pid:444, 
          comment="qwer" 
        }

users collection

        { 
          uid:12345, 
          name:"john" 
        },

        { 
          uid:99999,
          name:"mia"  
        }

May I know the command how to insert these collections in mongodb by adding reference between two collections usind dbref? comments in uid must refer the users uid.


回答1:


Database References (DBRefs) are a convention for storing IDs related to other collections, but are not a feature supported by the MongoDB server (i.e. a "join"). Depending on the language driver you are using to access MongoDB, there may be some support for following DBRefs and fetching the related documents .. but this does involve additional queries, the same as if you did so manually.

So the pseudo code for finding comments related to users in separate collections is something like:

  1. find({..}) users of interest
  2. For each user found
  3. ... find({uid:...}) all comments for that user

Depending on your use case, you may want to consider embedding information rather than linking. For example, the comments collection may actually be more appropriate embedded inside a posts collection (each post on the site has many embedded comments). Embedded comments could contain some basic user information such as a display name so you do not have to look this up in the users collection in order to render a page.

For more information see:

  • MongoDB docs on Schema Design

  • Designing MongoDB Schemas with Embedded, Non-Embedded and Bucket Structures



来源:https://stackoverflow.com/questions/12207084/dbref-command-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!