Set up two practice collections
Run this setup in mongosh on a development MongoDB instance. Use an empty scratch database named keplergrid_lookup. The fixture gives one customer two orders, one customer one order, and one customer zero orders.
const scratch = db.getSiblingDB("keplergrid_lookup")
scratch.customers.insertMany([
{ _id: "C-100", name: "Harbor Books" },
{ _id: "C-200", name: "Juniper Market" },
{ _id: "C-300", name: "Maple Workshop" }
])
scratch.orders.insertMany([
{ _id: "O-101", customerId: "C-100", item: "Notebook" },
{ _id: "O-102", customerId: "C-100", item: "Pencils" },
{ _id: "O-201", customerId: "C-200", item: "Envelopes" }
])
Join orders to customers with $lookup
Connect KeplerGrid to the MongoDB instance in Read only mode with permission to read both collections. Open keplergrid_lookup.customers, select Aggregation → JSON, paste this pipeline, and click Run pipeline.
[
{ "$sort": { "_id": 1 } },
{ "$lookup": {
"from": "orders",
"localField": "_id",
"foreignField": "customerId",
"as": "orders"
} }
]
The first stage orders the input customers by ID. The join compares each customer's _id with orders.customerId in the same database. The as field names the array that receives the matches. This pipeline returns reshaped documents and leaves both collections untouched.
Compare the stage input and output
- Switch to Stages and select
$lookup. - Under Input, each customer has an
_idandname. Under Output, the same customers also have anordersarray. Each panel previews up to five documents. - Compare the first customer with the last.
C-100has two matching orders.C-300still appears withorders: []. This is the left outer join behavior.
With this practice data, the output for those two customers looks like this. The order of entries inside the joined array can vary.
[
{
"_id": "C-100",
"name": "Harbor Books",
"orders": [
{ "_id": "O-101", "customerId": "C-100", "item": "Notebook" },
{ "_id": "O-102", "customerId": "C-100", "item": "Pencils" }
]
},
{
"_id": "C-300",
"name": "Maple Workshop",
"orders": []
}
]
Click Pipeline results to leave stage inspection. Select JSON view in the results toolbar to see the nested arrays in all three returned documents.
Check why a match is empty
- Verify the
fromcollection name and the field paths on both sides. In this example,customerIdbelongs toorders. - Check the stored BSON types. The string
"C-100"matches a string with that value. A string containing an ObjectId's hexadecimal text will not match an actual ObjectId. - On a larger collection, an index on the foreign field can help this equality lookup. Here that means
orders.customerId. Compare the plan on your own data before adding an index.
To see one row per order and keep customers without orders, flatten the joined array with $unwind.
Learn more about debugging aggregation stages or reading a MongoDB Explain plan.
Use a pipeline inside $lookup to filter the joined orders.
To combine rows from two collections into one result, use $unionWith.