Home > Blockchain >  To join or not to join on MongoDB?
To join or not to join on MongoDB?

Time:10-21

I have this hypothetical situation where there is a person and the address where he/she lives.

I know I can either create a collection Person (with name, age etc) and a collection Address (with a ""foreign key"" person_id and then perform a join in order to find the person's name inside address collection) or create only one collection Address and, instead of person_id, I can have person's properties inside address collection.

I looked for the most appropriate solution on the internet and I found both. I've already read about $lookup and I'm still confused about the solution.

I'm not an expert on NoSQL, and I'd like to know more opinions about what's the most appropriate solution to implement this.

CodePudding user response:

In this use-case, it would be best to keep all user addresses inside the user itself.

So, you would add address property to the user model, that will be an array, and you put all user addresses inside.

This approach is best here because of the following:

  1. When you fetch the user, the address information will be there already, so you don't have to perform $lookup, which will increase the performance.

  2. You don't have to maintain 2 collections, but only one.

  3. You don't have to be worry about scaling, because each user will probably have only a few addresses, and not thousands or tens of thousands of them.


Note: If use-case is that the user can potentially have thousands or tens of thousands of addresses, then you should go ahead with 2 collections, because each MongoDB document have the limit of 16MB, so you can not put all addresses inside the user.

  • Related