Create Document References
In this step, you'll learn how to create document references in MongoDB, which is a fundamental technique for establishing relationships between different collections.
First, let's start the MongoDB shell:
mongosh
We'll create two collections to demonstrate document referencing: authors
and books
. This is a common scenario where books are linked to their authors.
Create the authors collection:
use library_database
db.authors.insertMany([
{
_id: ObjectId("660a1f5c9b8f8b1234567890"),
name: "Jane Austen",
nationality: "British"
},
{
_id: ObjectId("660a1f5c9b8f8b1234567891"),
name: "George Orwell",
nationality: "British"
}
])
Example output:
{
acknowledged: true,
insertedIds: {
'0': ObjectId("660a1f5c9b8f8b1234567890"),
'1': ObjectId("660a1f5c9b8f8b1234567891")
}
}
Now, let's create the books collection with references to authors:
db.books.insertMany([
{
title: "Pride and Prejudice",
author_id: ObjectId("660a1f5c9b8f8b1234567890"),
year: 1813
},
{
title: "1984",
author_id: ObjectId("660a1f5c9b8f8b1234567891"),
year: 1949
}
])
Example output:
{
acknowledged: true,
insertedIds: {
'0': ObjectId("660b2a1c9b8f8b1234567892"),
'1': ObjectId("660b2a1c9b8f8b1234567893")
}
}
Let's verify the references by querying books with their author details:
db.books.aggregate([
{
$lookup: {
from: "authors",
localField: "author_id",
foreignField: "_id",
as: "author_details"
}
}
])
This demonstrates how to create document references in MongoDB. We've linked books to their authors using the author_id
field, which contains the ObjectId of the corresponding author.