MongoDB normalization, foreign key and joining

MongoDB doesn’t support server side foreign key relationships, normalization is also discouraged. You should embed your child object within parent objects if possible, this will increase performance and make foreign keys totally unnecessary. That said it is not always possible, so there is a special construct called DBRef which allows to reference objects in a different collection. This may be then not so speedy because DB has to make additional queries to read objects but allows for kind of foreign key reference.

Still you will have to handle your references manually. Only while looking up your DBRef you will see if it exists, the DB will not go through all the documents to look for the references and remove them if the target of the reference doesn’t exist any more. But I think removing all the references after deleting the book would require a single query per collection, no more, so not that difficult really.

If your schema is more complex then probably you should choose a relational database and not nosql.

There is also a book about designing MongoDB databases: Document Design for MongoDB

UPDATE The book above is not available anymore, yet because of popularity of MongoDB there are quite a lot of others. I won’t link them all, since such links are likely to change, a simple search on Amazon shows multiple pages so it shouldn’t be a problem to find some.

See the MongoDB manual page for ‘Manual references’ and DBRefs for further specifics and examples

Leave a Comment