0PricingLogin
MongoDB Academy · Lesson

Referencing: One-to-Many and Many-to-Many

Learners will store ObjectId references across collections and use $lookup to join them at query time.

What Is Referencing?

Referencing means storing an ObjectId (or another unique identifier) inside one document that points to a document in a different collection, similar to a foreign key in relational databases. Instead of nesting data, you link it. This approach is essential when the child count is large, when children are shared among multiple parents, or when children need to be queried independently.

One-to-Many With References

In a one-to-many relationship a single parent has many children. A user can have hundreds of orders—far too many to safely embed. Instead, each order document stores a userId reference pointing back to the parent user. This keeps the user document small while allowing unbounded order growth.

// users collection
db.users.insertOne({ _id: ObjectId('u1'), name: 'Alice', email: 'alice@example.com' });

// orders collection — each order references the user
db.orders.insertMany([
  { _id: ObjectId('o1'), userId: ObjectId('u1'), total: 49.99, status: 'shipped' },
  { _id: ObjectId('o2'), userId: ObjectId('u1'), total: 120.00, status: 'pending' }
]);

All lessons in this course

  1. Embedding: One-to-Few Relationships
  2. Referencing: One-to-Many and Many-to-Many
  3. The Unbounded Array Anti-Pattern
  4. Schema Design Decision Framework
← Back to MongoDB Academy