References and Embedding
DBRefs, $lookup, and population patterns
Skills taught: mongodb.relations
Manual Reference Pattern
The simplest form of referencing is storing the _id of one document inside another. This is the MongoDB equivalent of a SQL foreign key — but MongoDB does not enforce it. Your application code is responsible for data integrity.
// users collection
{ _id: ObjectId('u001'), name: 'Alice', email: 'alice@example.com' }
// posts collection — references users by _id
{ _id: ObjectId('p001'), title: 'Intro to MongoDB', authorId: ObjectId('u001'), body: '...' }
// Two-step fetch: get post, then get its author
const post = await db.collection('posts').findOne({ _id: postId });
const author = await db.collection('users').findOne({ _id: post.authorId });
const fullPost = { ...post, author };
// Two-step fetch with batch (N posts → 1 user query instead of N)
const posts = await db.collection('posts').find({ status: 'published' }).toArray();
const authorIds = [...new Set(posts.map(p => p.authorId))];
const authors = await db.collection('users').find({ _id: { $in: authorIds } }).toArray();
const authorsMap = Object.fromEntries(authors.map(a => [a._id.toString(), a]));
const enrichedPosts = posts.map(p => ({ ...p, author: authorsMap[p.authorId.toString()] }));
$lookup — Server-Side Join
$lookup is an aggregation pipeline stage that performs a left outer join between two collections. It's MongoDB's server-side JOIN — the database does the work, not your application code.
// Join orders with the user who placed them
const ordersWithUsers = await db.collection('orders').aggregate([
// Stage 1: Filter to recent orders only
{ $match: { status: 'completed', placedAt: { $gte: new Date('2026-01-01') } } },
// Stage 2: Join with users collection
{
$lookup: {
from: 'users', // foreign collection
localField: 'userId', // field in orders
foreignField: '_id', // field in users
as: 'user' // output array field name
}
},
// Stage 3: $lookup returns an array — $unwind converts [user] to user
{ $unwind: '$user' },
// Stage 4: Shape the output
{
$project: {
orderId: 1,
total: 1,
'user.name': 1,
'user.email': 1
}
}
]).toArray();
Pipeline $lookup (Advanced)
Since MongoDB 3.6, $lookup supports a pipeline form for complex join conditions — joining on multiple fields, adding filters on the joined documents, or joining computed values.
// Advanced $lookup with pipeline — join products with their current discounts
const productsWithDiscounts = await db.collection('products').aggregate([
{
$lookup: {
from: 'discounts',
let: { productId: '$_id', category: '$category' }, // variables from parent
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$productId', '$productId'] }, // match by id
{ $gte: ['$validUntil', new Date()] } // only active discounts
]
}
}
},
{ $sort: { discountPct: -1 } }, // best discount first
{ $limit: 1 } // only the top discount
],
as: 'bestDiscount'
}
},
{ $unwind: { path: '$bestDiscount', preserveNullAndEmptyArrays: true } }
]).toArray();
Tip: Always create an index on the foreignField used in $lookup. Without an index on users._id (which is auto-indexed), $lookup must scan the entire foreign collection for each document — O(N×M) performance.
Mongoose populate() — ODM-Level Joins
If you're using Mongoose (the Node.js MongoDB ODM), .populate() automatically fetches referenced documents. Under the hood, it makes a secondary find() query with { _id: { $in: [...ids] } }.
const mongoose = require('mongoose');
// Define schemas with references
const userSchema = new mongoose.Schema({
name: String,
email: String
});
const postSchema = new mongoose.Schema({
title: String,
body: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, // reference
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);
// Find all posts and populate author's name and email
const posts = await Post.find({ status: 'published' })
.populate('author', 'name email') // only fetch name and email fields
.populate('comments') // fetch all comment fields
.lean(); // return plain objects, not Mongoose documents (faster)
// Nested populate — populate a field inside a populated document
const post = await Post.findById(id)
.populate({
path: 'comments',
populate: { path: 'author', select: 'name avatar' } // author inside each comment
});
$lookup vs Mongoose populate() vs Manual Fetch
- $lookup (Aggregation): Server-side join in the aggregation pipeline
- Manual Fetch + Batch: Fetch parent docs, then batch-fetch referenced docs by IDs
Frequently Asked Questions
Does Mongoose support population?
Yes. Mongoose's .populate() method follows references declared in schemas and fetches referenced documents automatically. Internally it uses { _id: { $in: [...ids] } } to batch-fetch all referenced documents in one extra query.
Should I use $lookup or manage joins in my application code?
For complex joins with filtering on the joined collection, use $lookup — it's more efficient because the join happens before data is sent to your app. For simple parent-child fetches where you cache each collection separately, two separate queries can be more cache-friendly and simpler to reason about.
Does MongoDB enforce referential integrity?
No. MongoDB does not enforce foreign key constraints. If you delete a user, their referenced posts still exist with a dangling authorId. Your application or a cleanup job must handle orphaned references.