If you want to join between two or more collection then use lookup() method.
Syntax:-
db.collectionName.aggregate([ { $lookup: { from: 'otherCollection', localField: 'collection_fieldname', foreignField: 'otherCollection_fieldname', as: 'collectionDetails' } } ]).toArray();
If you have two collections
1) employees collection which has 3 documents
[ { "_id" : ObjectId("5f26e736deec6e20ea057831"), "name" : "John", "age" : 35, "department" : "department A", "salary" : 200000 }, { "_id" : ObjectId("5f26e9dedeec6e20ea057833"), "name" : "Tony", "age" : 31, "department" : "department B", "salary" : 40000 }, { "_id" : ObjectId("5f26e9dedeec6e20ea057835"), "name" : "Andrew", "age" : 33, "department" : "department C", "salary" : 20000 } ]
2) department collection
[ { "_id" : ObjectId("5f27bfaddeec6e20ea057836"), "name" : "department A", "floor" : 5, "facility" : "standard" }, { "_id" : ObjectId("5f27bfaddeec6e20ea057837"), "name" : "department B", "floor" : 4, "facility" : "good" }, { "_id" : ObjectId("5f27bfaddeec6e20ea057838"), "name" : "department C", "floor" : 3, "facility" : "normal" } ]
Now you want to get the employees collection document with department details
db.employees.aggregate([ { $lookup: { from: 'department', localField: 'department', foreignField: 'name', as: 'departmentDetails' } } ]).toArray();
Output:-
[ { "_id" : ObjectId("5f26e736deec6e20ea057831"), "name" : "John", "age" : 35, "department" : "department A", "salary" : 200000, "departmentDetails" : [ { "_id" : ObjectId("5f27bfaddeec6e20ea057836"), "name" : "department A", "floor" : 5, "facility" : "standard" } ] }, { "_id" : ObjectId("5f26e9dedeec6e20ea057833"), "name" : "Tony", "age" : 31, "department" : "department B", "salary" : 40000, "departmentDetails" : [ { "_id" : ObjectId("5f27bfaddeec6e20ea057837"), "name" : "department B", "floor" : 4, "facility" : "good" } ] }, { "_id" : ObjectId("5f26e9dedeec6e20ea057835"), "name" : "Andrew", "age" : 33, "department" : "department C", "salary" : 20000, "departmentDetails" : [ { "_id" : ObjectId("5f27bfaddeec6e20ea057838"), "name" : "department C", "floor" : 3, "facility" : "normal" } ] } ]