This pattern helps connect one item to many related items in different collections. It keeps data organized and easy to update.
0
0
One-to-many referencing pattern in MongoDB
Introduction
You have a list of books and each book has many reviews.
A blog post with many comments.
A customer with many orders.
A teacher with many students.
A playlist with many songs.
Syntax
MongoDB
/* Store references (IDs) of many related documents in an array */ { _id: ObjectId("..."), name: "Parent Item", relatedItems: [ObjectId("..."), ObjectId("..."), ...] }
The parent document holds an array of IDs pointing to many child documents.
This keeps data separate but linked, so you can find related items easily.
Examples
The author document stores IDs of books they wrote.
MongoDB
/* Example: Author with many books */ { _id: ObjectId("507f1f77bcf86cd799439011"), name: "Jane Doe", books: [ObjectId("507f1f77bcf86cd799439012"), ObjectId("507f1f77bcf86cd799439013")] }
Each book is stored separately with its own details.
MongoDB
/* Book document */ { _id: ObjectId("507f1f77bcf86cd799439012"), title: "Learn MongoDB", pages: 200 }
Sample Program
This example shows how an author references many books by their IDs. Then we find the author and get all their book titles by looking up the books collection.
MongoDB
/* Create authors and books collections with referencing */ db.authors.insertOne({ _id: ObjectId("507f1f77bcf86cd799439011"), name: "Jane Doe", books: [ObjectId("507f1f77bcf86cd799439012"), ObjectId("507f1f77bcf86cd799439013")] }); db.books.insertMany([ { _id: ObjectId("507f1f77bcf86cd799439012"), title: "Learn MongoDB", pages: 200 }, { _id: ObjectId("507f1f77bcf86cd799439013"), title: "Advanced MongoDB", pages: 350 } ]); /* Find author and list their book titles */ const author = db.authors.findOne({_id: ObjectId("507f1f77bcf86cd799439011")}); const books = db.books.find({_id: {$in: author.books}}).toArray(); books.map(book => book.title).join(", ");
OutputSuccess
Important Notes
Referencing keeps data smaller and avoids duplication.
You need to do extra queries to get related data.
Good for when related data changes often or is large.
Summary
One-to-many referencing links one document to many others using IDs.
It keeps data organized and easy to update.
Use it when you want to keep related data separate but connected.