Search on multiple collections in MongoDB

前端 未结 7 1965
自闭症患者
自闭症患者 2020-12-01 01:28

I know the theory of MongoDB and the fact that is doesn\'t support joins, and that I should use embeded documents or denormalize as much as possible, but here goes:

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 01:51

    You'll find MongoDB easier to understand if you take a denormalized approach to schema design. That is, you want to structure your documents the way the requesting client application understands them. Essentially, you are modeling your documents as domain objects with which the applicaiton deals. Joins become less important when you model your data this way. Consider how I've denormalized your data into a single collection:

    {  
        _id: 1, 
        first_name: 'Bill', 
        last_name: 'Gates', 
        suburb: 'Suburb A',
        state: 'LA',
        child : [ 3 ]
    }
    
    { 
        _id: 2, 
        first_name: 'Steve', 
        last_name: 'Jobs', 
        suburb: 'Suburb C',
        state 'NY',
        child: [ 4 ] 
    }
    { 
        _id: 3, 
        first_name: 'Little Billy', 
        last_name: 'Gates',
        suburb: 'Suburb A',
        state: 'LA',
        parent : [ 1 ]
    }
    
    {
        _id: 4, 
        first_name: 'Little Stevie', 
        last_name: 'Jobs'
        suburb: 'Suburb C',
        state 'NY',
        parent: [ 2 ]
    }
    

    The first advantage is that this schema is far easier to query. Plus, updates to address fields are now consistent with the individual Person entity since the fields are embedded in a single document. Notice also the bidirectional relationship between parent and children? This makes this collection more than just a collection of individual people. The parent-child relationships mean this collection is also a social graph. Here are some resoures which may be helpful to you when thinking about schema design in MongoDB.

提交回复
热议问题