Fastest query help to produce and make a relation between documents

Hi, I am new to mongodb and find a quick and efficient way to perform following task. the scenario is as follows

i have following 3 tables

  1. users -> having user information - thousands of users
  2. contacts -> list of all contacts of users (a user can have many phone numbers like phonebook contact list) - millions of contacts
  3. contact_users -> i don’t know how to explain is but what i need is to make contact syncing just like whatspp is doing like display the contacts from phonebook who have whatsapp account.
    so basically it will make the relation between phone numbers and display on user side that which account have whatsapp on this same number. I hope it will make sense.

one way that I know is the traditional way like get the contacts of 1 person, loop through all the contacts, find the matching and save in 3rd table. it will be long process, slow down the process and may be timeout at some certain stage

my question is how to make the best and fastest way to perform this process.

Hi @mehhfooz!

Welcome to the MongoDB Community.

There are some design patterns for data modeling on MongoDB. The following link shows a summary of them: https://www.mongodb.com/blog/post/building-with-patterns-a-summary

One of the advantages of using a document-store like MongoDB is the flexibility to store data as-is, without having to decompose an object (like your Users).

I’m not sure if I fully understand your case, but my best guess based on my understanding would be to have a “users” collection with documents using the following schema:

{
  "name": "Bruce Wayne",
  "nickname": "Batman",
  "contacts": [
    {
      "name": "Robin",
      "title": "Partner in crime",
      "phones": ["999-999-9999", "333-333-3333"]
    },
    {
      "name": "Albert",
      "title": "Friend",
      "phones": ["111-111-1111", "444-444-4444"]
    }
  ]
}

Contacts is an array of people in Bruce’s phonebook.

Hope it helps.

All the best,

Rodrigo
(a.k.a. Logwriter)