Querying data with a common key across multiple collections under same database

Okay so this is my first time in mongoDB.
Consider that I have a classroom database which has 5 collections, history, geography, science, mathematics and politics. In each collection, every entry represents a student’s perfomance in that subject.
The rollnum field uniquely identifies each student in a collection.

Now is there a way to get grades of the given rollnum from all the 5 collections, from a single query?

Also, I am working with Node.js if that helps.

Hello @Akash_Shanmugaraj, Welcome to the MongoDB community forum!

I want to suggest you make one collection with students and each will have an object with grades like:

[
  {
    rollnum: 1,
    grades: {
      history: A,
      geography: B,
      science: A,
      mathematics: C,
      politics: B
    }
  },
  {
    rollnum: 2,
    grades: {
      history: B,
      geography: C,
      science: A,
      mathematics: A,
      politics: C
    }
  },
]

And when you want to change the grades of a certain student, you just refer to his rollnum

1 Like

Thanks for the reply @Gleb_Ivanov!

Actually, there are extra fields like percentile, date of completion, etc.
And I am talking about a scale of over 80 databases, 3000 collections and about 4,000 to 6,000 pings a day, within a short span.

Would this be, say time efficient and query efficient, rather than having 5 separate find query for each collection?

I can’t say anything about this, because unfortunately I haven’t worked with projects of this size yet.

I would recommend a slight variation of this that uses the attribute pattern.

{
    rollnum: 1,
    grades: [
      { class:history, grade:A },
      { class:geography, grade: B },
      { class:science, grade: A },
      { class:mathematics, grade: C },
      { class:politics, grade: B }
    ]
  },
  {
    rollnum: 2,
    grades: [
      { class:history: grade:B } ,
      /* ... */
    ]
  },

Yes it will.

With

you are about to implement the massive number of collection anti-pattern.

With the attribute pattern you may easily have an object rather than a single grade field such as:

{
    rollnum: 1,
    grades: [
      { class:history, grade: A, percentile: x, completion_date: y } ,
      { class:geography, grade: B , /* ... */ } ,
      /* ... */
    ]
  }