Skip to content

Instantly share code, notes, and snippets.

@khaledosman
Last active August 6, 2020 09:58
Show Gist options
  • Save khaledosman/ecefb9a94cf1a1b72e17ab2b70a23351 to your computer and use it in GitHub Desktop.
Save khaledosman/ecefb9a94cf1a1b72e17ab2b70a23351 to your computer and use it in GitHub Desktop.
how to choose between MongoDB Embedded documents vs Separate collections
  1. Can you query events separately or are they always tied to a calendar? do you need pagination for events? Pagination for embedded documents is complicated or not as flexible/doable
  2. is it a one-to-one or one-to-many relations? can one event be in multiple calendars?
  3. if so can you edit/delete this event?, if you need to update the event and you have it as an embedded document instead of a separate collection, then you might have the problem of having to update the same event in multiple documents and ensuring data-consistency
  4. separate collection is usually cleaner, but its also less performant, because to get events for each calendar, you need to use .populate() which makes separate queries to get each event for each calendar when you query a calendar. A better idea is probably to query it the other way around (the events collection instead), i.e query all events by a specific calendar, thus reducing the number of queries needed if you were to query it the other way around.
  5. if you can think of event as a separate thing in your application that can exist outside/without a calendar then make it a separate collection, otherwise i would put it as an embedded document.
  6. embedded documents might also slow down your queries, if you query for calendars the database would still need to query all the big nested JSON objects of the events that are part of each calendar, to optimize your query for this case you would need to use .select() to tell the database to omit events from the documents returned or return specific fields only when they’re not needed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment