mongoDB: stores post_id in User object or user_id in Post object

In case I use mongoDB for a site that do something common like social media platform or a forum. It does the following things in descending order of frequency:

  1. it can list all posts in one page, and show who posts them.
  2. A user can posts a post, then it will be recorded that the post belongs to that user
  3. It can list all post a specific user posts

How should I structure that?
If I have two collections, Posts and Users.
How can I decide whether to:
Put the post_id inside User object
or
Put the user_id inside Post object?
Or both?

My intuition is that, for efficiency I can do both (so it is duplicated). It is because this can make the query simpler. But, such duplication would have some side effects like inconsistency, right?

Because I am not a database expert. I do not know if my intuition is right. thanks.

I’m still learning mongo, so take it FWIW.

In a relational database (SQL), you would put the id in both tables, and use the piece of information to do JOINs on your table. Pretty simple, done.

In a mongodb, you can put the ids in both collections and make 2 independent find operations to get all the data you need to display a page. But that doesnt seem efficient.

There is no JOIN in mongo, but take a look at the $lookup function. It’s almost equivalent to a JOIN query.

1 Like