Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

In relational world we have Foreign Keys to reference other entities. But how do document-oriented databases like MongoDb, CouchDb, RavenDb implement references among entities?

Update. StackExchange related example. We have Question entity and its tags. Each tag, is a separate entity so it has its properties (for example, description). How can I reference tags for some Question?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

You can do the same thing as in RMDBs, you reference by identifiers. I use MongoDB, so we can talk about this from that point.

Tag:

{
  _id: ObjectId('tag id'),
  tag_name: "nosql",
  tag_description: "blahblah' 
}

Then in the Post

{
  _id: ObjectId('post id'),
  tags: [
    ObjectId('tag1 id'),
    ObjectId('tag2 id')
  ],
  title: "title",
  // etc..
}

When you load a Post object you can either pull your tags documents as well, or you can pull them from cache. Often you use a ODM (instead of ORM) and it can often handle these references for you. For example, in Mongoid for Rails, you would just say :has_many :tags and it would figure out the rest for you. When you call post.tags it would just return an array of the tags associated with post.

share|improve this answer
    
Does this give the constraint a foreign key gives in a RDBMS? What happens if the tag document is deleted? –  johannes Aug 26 '12 at 22:41
    
There are no constraints. The application will have to deal with that. –  Travis Aug 27 '12 at 12:29

Easy; they don't.

If you want join abilities, you have to implement them in your client code. Some of these APIs do it a little easier by defining a 'Key' type that makes it easy to store and use references, but you have to do a second fetch to get the referenced entity.

share|improve this answer
    
Could you please clarify how I can solve a task which I added to Update by document-oriented database? –  Idsa Oct 9 '11 at 13:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.