Example 1 — Sample Data
Imagine three orders pointing at two customers (plus one orphan customerId). Customers include an active flag for the pipeline join in Example 4.
db.customers.drop()
db.orders.drop()
db.customers.insertMany([
{ _id: 1, name: "Acme", city: "Austin", active: true },
{ _id: 2, name: "Beta", city: "Boston", active: false }
])
db.orders.insertMany([
{ _id: "A100", customerId: 1, total: 40 },
{ _id: "B200", customerId: 2, total: 15 },
{ _id: "C300", customerId: 9, total: 99 }
]) How the Data Is Stored in MongoDB
After the inserts, MongoDB keeps two collections. Run find() on each to see what you stored:
db.customers.find()
db.orders.find() Read the join keys like this:
| Collection / field | Example | Plain English |
|---|---|---|
orders.customerId | 1, 2, 9 | Foreign key on each order (local side of the join) |
customers._id | 1, 2 | Customer id matched by $lookup (foreign side) |
orders._id | "A100" | Order id (not used for the join in these examples) |
customers.active | true / false | Filter flag for pipeline $lookup in Example 4 |
Join key (equality $lookup):
orders.customerId ──matches──► customers._id
A100 customerId 1 → Acme (_id 1)
B200 customerId 2 → Beta (_id 2)
C300 customerId 9 → (no customer _id 9) How It Works
- Reset collections.
drop()clears old tutorial data from both sides. - Insert customers. Each row has
_id, name, city, andactive. - Insert orders. Each order stores
customerIdpointing at a customer_id. - find() confirms shape. Same documents you inserted—ready for
$lookupin Examples 2–4.

