7

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?

Jonas
  • 14,867
  • 9
  • 69
  • 102
SiberianGuy
  • 4,753
  • 6
  • 34
  • 46
  • The document-oriented form of this is by embedding the related object, so you might end up with multiple copies of your tags. Having the explicit relations is modeling relational in JSON. So why not use a relational database? or use two databases, one relational and one documental? – Pablo Pazos Feb 21 '17 at 05:17

2 Answers2

6

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.

Travis
  • 1,329
  • 6
  • 14
4

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.

Javier
  • 9,888
  • 1
  • 26
  • 35