Consider below Mongo DB 3.2 Document,
Clients Collection Document
{
"_id" : "gcJk4eRRo2WCbgWSL",
"services" : [
"2tLX8ALYfRvbgiurZ",
"wfE5MqgHfu9QKtK7d",
"MEZtABSEeskuRivXJ"
]
}
Also, Services Collection Documents
{ "_id" : "2tLX8ALYfRvbgiurZ", "name" : "GSTR 1" }
{ "_id" : "wfE5MqgHfu9QKtK7d", "name" : "GSTR 2" }
{ "_id" : "MEZtABSEeskuRivXJ", "name" : "GSTR 3" }
Now, the values in services array field in Clients is associated to _id of Services Collection.
Below is the code that I am currently executing,
db.getCollection('Clients').aggregate(
[
{ "$unwind" : { path: "$services"}},
{
"$lookup" : { from: "Services", localField: "services", foreignField: "_id", as: "services" }
},
{ "$unwind" : { path: "$services", preserveNullAndEmptyArrays: true }},
{ "$project" : {
_id : 1, services: '$services.name'
}
}
]
);
Output of Above code execution is,
{ "_id" : "gcJk4eRRo2WCbgWSL", "services" : "GSTR 1" }
{ "_id" : "gcJk4eRRo2WCbgWSL", "services" : "GSTR 2" }
{ "_id" : "gcJk4eRRo2WCbgWSL", "services" : "GSTR 3" }
But Expected output is as below,
{
"_id" : "gcJk4eRRo2WCbgWSL",
"services" : "GSTR 1, GSTR 2, GSTR 3"
}
Any help is highly appreciated.