#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read
Question 8 of 27medium

How do you model relationships in MongoDB?

Handling one-to-one, one-to-many, many-to-many.

What You'll Learn

  • One-to-one relationships
  • One-to-many relationships
  • Many-to-many relationships

One-to-One

Embedded (Preferred)

code.jsJavaScript
{
  _id: ObjectId("..."),
  name: "John",
  profile: {
    bio: "Developer",
    website: "john.dev",
    social: { twitter: "@john" }
  }
}

Referenced

code.jsJavaScript
// users collection
{ _id: 1, name: "John", profileId: ObjectId("profile1") }

// profiles collection
{ _id: ObjectId("profile1"), bio: "Developer" }

One-to-Many

Embedded (Few items)

code.jsJavaScript
{
  _id: ObjectId("..."),
  title: "Blog Post",
  comments: [
    { user: "Alice", text: "Great!" },
    { user: "Bob", text: "Thanks!" }
  ]
}

Referenced (Many items)

code.jsJavaScript
// posts collection
{ _id: 1, title: "Blog Post" }

// comments collection
{ _id: 1, postId: 1, user: "Alice", text: "Great!" }
{ _id: 2, postId: 1, user: "Bob", text: "Thanks!" }

// Query with $lookup
db.posts.aggregate([
  { $lookup: {
      from: "comments",
      localField: "_id",
      foreignField: "postId",
      as: "comments"
  }}
]);

Many-to-Many

code.jsJavaScript
// students collection
{ _id: 1, name: "Alice", courseIds: [101, 102] }

// courses collection
{ _id: 101, name: "Math", studentIds: [1, 2, 3] }

// Or use a junction collection
// enrollments: { studentId: 1, courseId: 101, enrolledAt: Date }