join two collections in mongodb using node js

Hi Friend Like Earlier Post today i would like to share my experience, Can we use Join in mongo DB like Sql?  Can We Use Where condition in mongo DB on Populated column?

Answer is YES. We can Use Join In Mongo DB and We can Use Condition on populated columns.

we can perform a left outer join by using the $lookup. The $lookup lets you specify which collection you want to join with the current collection, and which fields that should match. To apply condition on populated column use $unwind because look up return array and to access key need to use $unwind

Consider you have a “enquiries” collection and a “products” collection.
Enquiries collection have referance column for product.

Question is “want to accees Enquiry Data who enquire for product cotton shirt”

enquiries collection

[{
“_id”: “1”,
“enq_date”: “2019-06-27”,
“productid”: “1”
},{
“_id”: “1”,
“enq_date”: “2019-06-27”,
“productid”: “2”
},{
“_id”: “1”,
“enq_date”: “2019-06-27”,
“productid”: “1”
}]

products collection

[{
“_id”: “1”,
“product_name”: “cotton shirt”
},{
“_id”: “2”,
“product_name”: “cotton jeans”
}]

Querry is:

db.getCollection(‘enquiries’).aggregate([
{“$lookup”:{“from”:”products”,”localField”:”productid”,”foreignField”:”_id” ,”as” :”prod”}},
{“$unwind”:”$prod”},
{“$match”:{ “prod.product_name” : “cotton shirt”}},
])