You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: mongodb-code.md
+138Lines changed: 138 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -354,4 +354,142 @@ The operation results in the following document:
354
354
}
355
355
```
356
356
357
+
## Join 3 or more collections
358
+
359
+
Let's say we have 3 hypothetical collections in MongoDB: customers, orders, and orderItems.
360
+
361
+
Each customer has multiple orders, and each order has multiple order items.
362
+
363
+
364
+
### customers
365
+
366
+
```js
367
+
[
368
+
{
369
+
customer_id:1,
370
+
name:"Jim Smith",
371
+
email:"jim.smith@example.com"
372
+
},
373
+
{
374
+
customer_id:2,
375
+
name:"Bob Jones",
376
+
email:"bob.jones@example.com"
377
+
}
378
+
]
379
+
```
380
+
### orders
381
+
```js
382
+
[
383
+
{
384
+
order_id:1,
385
+
customer_id:1
386
+
},
387
+
{
388
+
order_id:2,
389
+
customer_id:1
390
+
}
391
+
]
392
+
```
393
+
394
+
### orderItems
395
+
```js
396
+
[
397
+
{
398
+
order_item_id:1,
399
+
name:"Foo",
400
+
price:4.99,
401
+
order_id:1
402
+
},
403
+
{
404
+
order_item_id:2,
405
+
name:"Bar",
406
+
price:17.99,
407
+
order_id:1
408
+
},
409
+
{
410
+
order_item_id:3,
411
+
name:"baz",
412
+
price:24.99,
413
+
order_id:2
414
+
}
415
+
]
416
+
```
417
+
418
+
### Desired Result
419
+
```js
420
+
[
421
+
{
422
+
customer_id:1,
423
+
name:"Jim Smith",
424
+
email:"jim.smith@example.com"
425
+
orders: [
426
+
{
427
+
order_id:1,
428
+
items: [
429
+
{
430
+
name:"Foo",
431
+
price:4.99
432
+
},
433
+
{
434
+
name:"Bar",
435
+
price:17.99
436
+
}
437
+
]
438
+
},
439
+
{
440
+
order_id:2,
441
+
items: [
442
+
{
443
+
name:"baz",
444
+
price:24.99
445
+
}
446
+
]
447
+
}
448
+
]
449
+
},
450
+
{
451
+
customer_id:2,
452
+
name:"Bob Jones",
453
+
email:"bob.jones@example.com"
454
+
orders: []
455
+
}
456
+
]
457
+
```
458
+
459
+
460
+
# Answer
461
+
462
+
Do nested lookup using lookup with pipeline,
463
+
464
+
1. ```$lookup``` with orders collection.
465
+
2. ```let```, define variable customer_id that is from main collection, to access this reference variable inside pipeline using ```$$``` like ```$$customer_id```.
466
+
3. ```pipeline``` can add pipeline stages same as we do in root level pipeline
467
+
4. ```$expr``` whenever we match internal fields it requires expression match condition, so ```$$customer_id``` is parent collection field that declared in let and $customer_id is child collection's/current collection's field
0 commit comments