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?

  • 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? Feb 21, 2017 at 5:17

2 Answers 2


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.


  _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.

  • Does this give the constraint a foreign key gives in a RDBMS? What happens if the tag document is deleted?
    – johannes
    Aug 26, 2012 at 22:41
  • There are no constraints. The application will have to deal with that.
    – Travis
    Aug 27, 2012 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.

  • Could you please clarify how I can solve a task which I added to Update by document-oriented database? Oct 9, 2011 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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