In this tutorial, we will learn how MongoDB, a popular NoSQL database, manages relationships between documents using two primary methods: Document References and Embedded Documents.
By the end of this tutorial, you should be able to understand and use MongoDB to establish connections between data using Document References and Embedded Documents.
MongoDB provides two ways to represent relationships between data, namely, Document References (Normalization) and Embedded Documents (Denormalization).
Document References involve creating references from one document to another. This method is beneficial when you have related data in different collections.
Embedded Documents allow you to store related data in a single document structure. This is useful when dealing with data that are closely related and will not require to be queried separately.
// User document
{
_id: ObjectId("5099803df3f4948bd2f98391"),
username: "jdoe",
email: "jdoe@example.com"
}
// Post document referencing User
{
_id: ObjectId("5099803df3f4948bd2f98394"),
content: "Hello, world!",
author: ObjectId("5099803df3f4948bd2f98391") // Reference to User document
}
In this example, we have a User document and a Post document. The author
field in the Post document is a reference to the User document.
// Post document with embedded comments
{
_id: ObjectId("5099803df3f4948bd2f98394"),
content: "Hello, world!",
comments: [
{
text: "Nice post!",
author: "jdoe"
},
{
text: "I agree with @jdoe",
author: "asmith"
}
]
}
In this example, the comments related to a post are stored directly within the Post document itself.
In this tutorial, we have covered Document References and Embedded Documents in MongoDB. You should now understand how to establish relationships between documents in MongoDB and when to use each method.
Exercise 1:
// Author document
{
_id: ObjectId("5099803df3f4948bd2f98392"),
name: "John Smith"
}
// Book document referencing Author
{
_id: ObjectId("5099803df3f4948bd2f98393"),
title: "MongoDB for Beginners",
author: ObjectId("5099803df3f4948bd2f98392") // Reference to Author document
}
Exercise 2:
// Blog post document with embedded comments
{
_id: ObjectId("5099803df3f4948bd2f98395"),
title: "Learning MongoDB",
content: "Today I learned...",
comments: [
{
text: "Great post!",
author: "asullivan"
},
{
text: "Thanks for sharing your learnings",
author: "bwilliams"
}
]
}
Remember, practice is key to mastering any concept, so feel free to manipulate the code examples and exercises to better understand the concepts. Happy coding!