I have three collections Subscribers
,Address
,Languages
Subscribers
schema has following record
{
"_id" : ObjectId("5a73fae80290f7eca89e99d4"),
"FirstName" : "Rahul",
"LastName" : "Shah",
"Address" : DBRef("Address", ObjectId("5a6ec9bda3baf2b516de5769")),
"Languages" : [
DBRef("Languages", ObjectId("5a6304ffc3c3f119fc0e60c9")),
DBRef("Languages", ObjectId("5a6ee970a3baf2b516de576b"))
]
}
Address
schema has following record
{
"_id" : ObjectId("5a6ec9bda3baf2b516de5769"),
"Address1" : "Vastrapur,
"Address2" : "Satellite",
"City" : "Ahmedabad",
"Country" : "India",
"State" : "Gujarat",
"ZipCode" : "380015",
"PhoneNumber" : "(987)654-3210",
"FaxNumber" : ""
}
Languages
schema has following record
{
"_id" : ObjectId("5a6304ffc3c3f119fc0e60c9"),
"Name" : "English",
"LanguageCulture" : "English",
"IsDeleted" : false
}
{
"_id" : ObjectId("5a6ee970a3baf2b516de576b"),
"Name" : "Hindi",
"LanguageCulture" : "Hindi",
"IsDeleted" : false
}
I want output be like as below
{
"_id" : ObjectId("5a73fae80290f7eca89e99d4"),
"FirstName" : "Rahul",
"LastName" : "Shah",
"Address" : {
"_id" : ObjectId("5a6ec9bda3baf2b516de5769"),
"Address1" : "Vastrapur",
"Address2" : " Satellite ",
"City" : " Ahmedabad ",
"Country" : " India ",
"State" : " Gujarat ",
"ZipCode" : " 380015 ",
"PhoneNumber" : "(987)654 - 3210 ",
"FaxNumber" : " "
},
"Languages" : [{
"_id" : ObjectId(" 5a6304ffc3c3f119fc0e60c9 "),
" Name" : " English ",
"LanguageCulture" : " English ",
"IsDeleted" : false
}, {
"_id" : ObjectId(" 5a6ee970a3baf2b516de576b "),
"Name" : " Hindi ",
"LanguageCulture" : " Hindi ",
"IsDeleted" : false
}
]
}
For that Im doing aggregation as below
db.Subscribers.aggregate([{
$project : {
"FirstName" : 1,
"LastName" : 1,
Address : {
$let : {
vars : {
refParts : {
$objectToArray : "$$ROOT.Address"
}
},
in : "$$refParts"
}
}
}
}, {
$match : {
"addressRefs" : {
$exists : true
}
}
}, {
$project : {
"FirstName" : 1,
"LastName" : 1,
"addressRefs" : {
$arrayElemAt : ["$addressRefs", 1]
}
}
}, {
$lookup : {
from : "Addresses",
localField : "addressRefs",
foreignField : "_id",
as : "address_data"
}
}, {
$project : {
"FirstName" : 1,
"LastName" : 1,
"AddressUuid" : {
$arrayElemAt : ["$address_data.uuid", 0]
}
}
}
])