SyntaxStudy
Sign Up
MongoDB Many-to-Many and Tree Structures
MongoDB Beginner 1 min read

Many-to-Many and Tree Structures

Many-to-many relationships in MongoDB are often implemented with an array of references on one or both sides. For example, a student enrolled in many courses can store an array of courseIds, and querying with $in on that array is fast with an index. Tree structures — categories, org charts, threaded discussions — can be modelled in several ways: parent reference (each node stores its parent _id), child references (parent stores an array of children), an array of ancestors (each node stores a full path from root), or a materialised path string like /root/electronics/laptops. The ancestors array pattern supports efficient subtree queries with $in and is one of the most practical tree representations in MongoDB.
Example
// MANY-TO-MANY — students and courses
db.students.insertOne({
  _id: ObjectId("s1"),
  name: "Dana",
  // Array of references
  enrolledCourseIds: [ObjectId("c1"), ObjectId("c2"), ObjectId("c3")]
})

// Find all students enrolled in course c1
db.students.find({ enrolledCourseIds: ObjectId("c1") })

// TREE — ancestors array pattern (category hierarchy)
db.categories.insertMany([
  { _id: 1, name: "Root",        ancestors: [] },
  { _id: 2, name: "Electronics", ancestors: [1] },
  { _id: 3, name: "Laptops",     ancestors: [1, 2] },
  { _id: 4, name: "Gaming",      ancestors: [1, 2, 3] }
])

// Find all descendants of Electronics (id=2)
db.categories.find({ ancestors: 2 })

// Materialised path pattern
db.categories.insertOne({
  _id: 5,
  name: "Ultrabooks",
  path: "/1/2/3/5"   // full path string
})

// Find all nodes under Electronics using regex
db.categories.find({ path: /^\/1\/2/ })