参考:官方文档

    1. db.orders.insert([
    2. { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
    3. { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
    4. { "_id" : 3 }
    5. ])
    6. db.inventory.insert([
    7. { "_id" : 1, "sku" : "almonds", "description": "product 1", "instock" : 120 },
    8. { "_id" : 2, "sku" : "bread", "description": "product 2", "instock" : 80 },
    9. { "_id" : 3, "sku" : "cashews", "description": "product 3", "instock" : 60 },
    10. { "_id" : 4, "sku" : "pecans", "description": "product 4", "instock" : 70 },
    11. { "_id" : 5, "sku": null, "description": "Incomplete" },
    12. { "_id" : 6 }
    13. ])
    1. '''
    2. SELECT *, inventory_docs
    3. FROM orders
    4. WHERE inventory_docs IN (SELECT *
    5. FROM inventory
    6. WHERE sku= orders.item);
    7. '''
    8. db.orders.aggregate([
    9. {
    10. $lookup:
    11. {
    12. from: "inventory",
    13. localField: "item",
    14. foreignField: "sku",
    15. as: "inventory_docs"
    16. }
    17. }
    18. ])
    1. {
    2. "_id" : 1,
    3. "item" : "almonds",
    4. "price" : 12,
    5. "quantity" : 2,
    6. "inventory_docs" : [
    7. { "_id" : 1, "sku" : "almonds", "description" : "product 1", "instock" : 120 }
    8. ]
    9. }
    10. {
    11. "_id" : 2,
    12. "item" : "pecans",
    13. "price" : 20,
    14. "quantity" : 1,
    15. "inventory_docs" : [
    16. { "_id" : 4, "sku" : "pecans", "description" : "product 4", "instock" : 70 }
    17. ]
    18. }
    19. {
    20. "_id" : 3,
    21. "inventory_docs" : [
    22. { "_id" : 5, "sku" : null, "description" : "Incomplete" },
    23. { "_id" : 6 }
    24. ]
    25. }