Search code examples
sqlmongodbforeign-keysnosql

Foreign keys in mongo?


enter image description here

How do I design a scheme such this in MongoDB? I think there are no foreign keys!


Solution

  • You may be interested in using a ORM like Mongoid or MongoMapper.

    http://mongoid.org/docs/relations/referenced/1-n.html

    In a NoSQL database like MongoDB there are not 'tables' but collections. Documents are grouped inside Collections. You can have any kind of document – with any kind of data – in a single collection. Basically, in a NoSQL database it is up to you to decide how to organise the data and its relations, if there are any.

    What Mongoid and MongoMapper do is to provide you with convenient methods to set up relations quite easily. Check out the link I gave you and ask any thing.

    Edit:

    In mongoid you will write your scheme like this:

    class Student
      include Mongoid::Document
    
        field :name
        embeds_many :addresses
        embeds_many :scores    
    end
    
    class Address
      include Mongoid::Document
    
        field :address
        field :city
        field :state
        field :postalCode
        embedded_in :student
    end
    
    class Score
      include Mongoid::Document
    
        belongs_to :course
        field :grade, type: Float
        embedded_in :student
    end
    
    
    class Course
      include Mongoid::Document
    
      field :name
      has_many :scores  
    end
    

    Edit:

    > db.foo.insert({group:"phones"})
    > db.foo.find()                  
    { "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }
    { "_id" : ObjectId("4df6540fe90592692ccc9941"), "group" : "phones" }
    >db.foo.find({'_id':ObjectId("4df6539ae90592692ccc9940")}) 
    { "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }
    

    You can use that ObjectId in order to do relations between documents.