MongoDB
Beginner
1 min read
Many-to-Many and Tree Structures
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/ })