Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB embedded documents vs. referencing by unique ObjectIds for a system user profile

Tags:

mongodb

nosql

I'd like to code a web app where most of the sections are dependent on the user profile (for example different to-do lists per person etc) and I'd love to use MongoDB. I was thinking of creating about 10 embedabble documents for the main profile document and keep everything related to one user inside his own document.

I don't see a clear way of using foreign keys for mongodb, the only way would be to create a field to_do_id with the type of ObjectId for example, but they would be totally unrelated internally, just happen to have the same Ids I'd have to query for.

  1. Is there a limit on the number of embedded document types inside a top level document that could degrade performance?
  2. How do you guys solve the issue of having a central profile document that most of the documents have to relate to in presenting a view per person?
  3. Do you use semi foreign keys inside MongoDb and have fields with ObjectId types that would have some other document's unique Id instead of embedding them?

I cannot feel what approach should be taken when. Thank you very much!

like image 698
78 Things Avatar asked Sep 09 '11 18:09

78 Things


1 Answers

  1. There is no special limit with respect to performance. The larger the document, though, the longer it takes to transmit over the wire. The whole document is always retrieved.
  2. I do it with references. You can choose between simple manual references and the database DBRef as per this page: http://www.mongodb.org/display/DOCS/Database+References
  3. The link above documents how to have references in a document in a semi-foreign key way. The DBRef might be good for what you are trying to do, but the simple manual reference is very efficient.

I am not sure a general rule of thumb exists for which reference approach is best. Since I use Java or Groovy mostly, I like the fact that I get a DBRef object returned. I can check for this datatype and use that to decide how to handle the reference in a generic way.

So I tend to use a simple manual reference for references to different documents in the same collection, and a DBRef for references across collections.

I hope that helps.

like image 110
dlaidlaw Avatar answered Sep 22 '22 23:09

dlaidlaw