Search code examples
mongodbmongodb-javanosql

What is the best practice for joins in MongoDB?


I have two class called School and Student as you see. I want to search for "students that school names are bla bla bla" and "schools that have students which has higher grade than 90". I read some documents but I am a little confused.

public class School extends BasicDBObject  {
  private int id;
  private String name;
  private String number;
  private List<Student> studentList = new ArrayList<Student>();,

  //getter and setters
}

public class Student extends BasicDBObject{
  private int id;
  private String name;
  private String grade;
  private School school;

  //getter and setters
}

Solution

  • MongoDB is not a relational database. It doesn't support joins. To simulate a join, you have to query the first collection, get the results, and then query the second collection with a large $in query filled with the applicable key values of the documents returned by the first query. This is as slow and ugly as it sounds, so the database schema should be designed to avoid it.

    For your example, I would add the school names to the Student documents. This would allow to satisfy both of your use-cases with a single query.

    Anyone coming from a relational database background would now say "But that's a redundancy! You've violated the second normal form!". That's true, but normalization is a design pattern specific to relational databases. It doesn't necessarily apply to document-oriented databases. So what design patterns are applicable for document-oriented databases? Tough call. It's a new technology. We are still figuring this out.