bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Node.js/Database Integration
Node.js•Database Integration

Node.js MongoDB Join

Join Collections

MongoDB is not a relational database, but you can perform a left outer join by using the $lookup stage.

The $lookup stage lets you specify which collection you want to join with the current collection, and which fields that should match.

Consider you have a "orders" collection and a "products" collection:

orders

[ { _id: 1, product_id: 154, status: 1 }
]

products

[ { _id: 154, name: 'Chocolate Heaven' }, { _id: 155, name: 'Tasty Lemons' }, {
 _id: 156, name: 'Vanilla Dreams' }
 ]

Example

Join the matching "products" document(s) to the "orders" collection:

let MongoClient = require('mongodb').MongoClient;
let url = "mongodb://127.0.0.1:27017/";
MongoClient.connect(url, function(err, db) {
 if (err) throw err;
 let dbo = db.db("mydb");
 dbo.collection('orders').aggregate([ { $lookup:
 {
 from: 'products',
 localField: 'product_id',
 foreignField: '_id',
 as: 'orderdetails'
 }
 }
 ]).toArray(function(err, res) {
 if (err) throw err;
 console.log(JSON.stringify(res));
 db.close();
});
});

Save the code above in a file called "demo_mongodb_join.js" and run the file:

Run "demo_mongodb_join.js"

C:\Users\
Your Name
>node demo_mongodb_join.js

Which will give you this result

[ { "_id": 1, "product_id": 154, "status": 1, "orderdetails": [ { "_id": 154, "name": "Chocolate Heaven" } ]
 }
]

As you can see from the result above, the matching document from the products collection is included in the orders collection as an array.

Previous

Node.js MongoDB Limit

Next chapter

Advanced Communication

Start with Node.js GraphQL

This chapter

Overview
24

Lessons

70m

Read time

1. Node.js MySQL2. Node.js MySQL Create Database3. Node.js MySQL Create Table4. Node.js MySQL Insert Into5. Node.js MySQL Select From6. Node.js MySQL Where7. Node.js MySQL Order By8. Node.js MySQL Delete9. Node.js MySQL Drop Table10. Node.js MySQL Update11. Node.js MySQL Limit12. Node.js MySQL Join13. Node.js MongoDB14. Node.js MongoDB Create Database15. Node.js MongoDB Create Collection16. Node.js MongoDB Insert17. Node.js MongoDB Find18. Node.js MongoDB Query19. Node.js MongoDB Sort20. Node.js MongoDB Delete21. Node.js MongoDB Drop22. Node.js MongoDB Update23. Node.js MongoDB Limit24. Node.js MongoDB Join

On this page

Join Collectionsordersproducts