Think of each user can like many posts or products that they want, this is a Many to Many relationships. In SQL we could have a table named
user_likes to store the user’s liked items.
Remember that, of course, a user can store thousand or perhaps millions.
But how to accomplish it in MongoDB? There are 3 scenarios or schemas that I can think of;
#1 The ??? Pattern
I don’t know what or how to name it, but with this pattern, we could have a collection that automatically creates 1 document for each user. This document would store all the liked items’ ID by the user.
The naming convention for every ID within this collection would be
user ID, therefore whenever we would like to get or compare items whether they’re liked by the user, we would just have to query this particular document that belongs to a user.
#2 Many to Many documents
Think of this collection is a pivot table in the SQL world, thus every document here are a pivot document that similar to pivot rows SQL.
Within every document, we will store the
user_id and the
#3 Document references
As stated here: Model One-to-Many Relationships with Document References — MongoDB Manual
items collection, we would store all the user ID who likes the item.
Thank you everyone at MongoDB.