Collection modelling ("multi-model" collections)


I’m creating an application which allows users define a schema for their documents and then create documents that will be validated against the schema. Document schemas can define “relations” between each other which means that when I query the documents I need to get related documents as well. Schemas also allow to set certain document properties as ‘sortable’ which means I’d need to create indexes for documents that have that schema.

All the validation is done on the application layer. I am however facing a dilemma of how to “model” my storage layer.

The approach I’m taking at the moment is inserting all documents into one collection no matter what schema they belong to. Which means that I’ll have a bunch of partial indexes that only index the documents where specific fields exist. I also have a relations collection with documents that have ‘from’ and ‘to’ ids (something akin to join tables).

It works well but I keep second-guessing this approach. Based on what I see in the wild the most common approach is to have a collection per schema. I’m not against it but it certainly makes for a more complex solution as I’d need to create more collections for the “join” tables and track more things overall.

My question is — am I missing something crucial in a the single collection approach that might render it as a bad one?

1 Like

Hello @Alexey_Golev! First of all, great question and thank you for being a part of the MongoDB Community! :smiling_face_with_three_hearts:

With regard to your question, is it okay to have documents of different shapes within the same collection? The short answer is YES! :dizzy: We actually have a pattern named after this exact use case, it’s called the Polymorphic Pattern.

You’re right that lots of people split up their data into separate collections, but IMHO it’s because they are used to doing the SQL way, not the MongoDB way.

tl;dr - You’re on the right track and I support your schema decision! :smiling_face_with_three_hearts:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.