What is Referencing in MongoDB: Explanation and Example
referencing means storing the _id of one document inside another document to link them. This creates a relationship between documents without embedding all data together, allowing flexible and efficient data management.How It Works
Referencing in MongoDB works like leaving a note with a friend's phone number instead of writing down their entire address. Instead of copying all the details of one document into another, you just store a reference to it using its unique _id. This way, you can find the related document when needed without repeating data.
Think of it as a library system: a book record might have a reference to the author’s record by storing the author’s ID. When you want to know more about the author, you look up the author’s document using that ID. This keeps data organized and avoids duplication.
Example
authors and books. Each book stores a reference to its author by the author's _id. This links the book to the author without copying all author details inside the book document.use library // Insert an author document const authorId = db.authors.insertOne({ name: "Jane Austen", birthYear: 1775 }).insertedId; // Insert a book document referencing the author by _id db.books.insertOne({ title: "Pride and Prejudice", authorId: authorId, publishedYear: 1813 }); // Find the book and then find its author using the reference const book = db.books.findOne({ title: "Pride and Prejudice" }); const author = db.authors.findOne({ _id: book.authorId }); printjson({ book: book, author: author });
When to Use
Use referencing when you want to keep related data in separate documents but still link them. This is helpful when the related data is large or changes often, so you avoid copying and updating it in many places.
For example, in an online store, you might store customer details separately from their orders. Each order references the customer by ID. This way, if the customer updates their address, you only change it once in the customer document.
Referencing is also good when you want to keep your data normalized, similar to how relational databases work, but still enjoy MongoDB’s flexibility.
Key Points
- Referencing stores the
_idof one document inside another to create a link. - It avoids data duplication by not embedding full documents.
- Useful when related data is large or updated frequently.
- Requires extra queries to fetch linked documents.
- Helps keep data organized and normalized.