Reputation: 11
I have 2 collections adminUser and departmentUser which are linked by field adminUserId
from adminUser collection and adminUserId
from departmentUser collection.
I want to merge these two collections which contain all fields of both collections whether data is common or uncommon between them. I tried by using aggregation but aggregation returns data with common fields only.
adminUser:
{
"adminUserId" : "1"
"userName" : "Smith",
"position" : "Head"
},
{
"adminUserId" : "2"
"userName" : "Joe",
"position" : "Lead"
},
{
"adminUserId" : "3"
"userName" : "Mark",
"position" : "Lead"
}
departmentUser:
{
"userId" : "1"
"userName" : "Leslie",
"position" : "Head",
"adminUserId" : ""
},
{
"userId" : "2"
"userName" : "Joe",
"position" : "Lead",
"adminUserId" : "2"
},
{
"userId" : "3"
"userName" : "Mark",
"position" : "Lead",
"adminUserId" : "3"
},
{
"userId" : "4"
"userName" : "Allen",
"position" : "Lead",
"adminUserId" : ""
}
Output:
{
"adminUserId" : "1"
"userName" : "Smith",
"position" : "Head"
},
{
"adminUserId" : "2"
"userName" : "Joe",
"position" : "Lead",
"departmentUserinfo":{
"userId" : "2"
"userName" : "Joe",
"position" : "Lead",
"adminUserId" : "2"
}
},
{
"adminUserId" : "3"
"userName" : "Mark",
"position" : "Lead",
"departmentUserinfo":{
"userId" : "2"
"userName" : "Mark",
"position" : "Lead",
"adminUserId" : "3"
}
},
{
"adminUserId" : ""
"userName" : "",
"position" : "",
"departmentUserinfo":{
"userId" : "1"
"userName" : "Leslie",
"position" : "Head",
"adminUserId" : ""
}
},
{
"adminUserId" : ""
"userName" : "",
"position" : "",
"departmentUserinfo":{
"userId" : "4"
"userName" : "Allen",
"position" : "Lead",
"adminUserId" : ""
}
}
Can anyone help?
Upvotes: 1
Views: 66
Reputation: 17925
Try this :
db.adminUser.aggregate([
{
$lookup:
{
from: "departmentUser",
localField: "adminUserId",
foreignField: "adminUserId",
as: "departmentUserinfo"
}
},
// As $lookup will result in an array i.e; departmentUserinfo will be an array, So getting first element out of it as we know it will always be [{}] --> If match found or [] --> If no match
{ $addFields: { departmentUserinfo: { $arrayElemAt: ['$departmentUserinfo', 0] } } }
])
Result :
/* 1 */
{
"_id" : ObjectId("5e1757b919c2d113022f4584"),
"adminUserId" : "1",
"userName" : "Smith",
"position" : "Head"
}
/* 2 */
{
"_id" : ObjectId("5e1757b919c2d113022f4585"),
"adminUserId" : "2",
"userName" : "Joe",
"position" : "Lead",
"departmentUserinfo" : {
"_id" : ObjectId("5e1757f219c2d113022f4588"),
"userId" : "2",
"userName" : "Joe",
"position" : "Lead",
"adminUserId" : "2"
}
}
/* 3 */
{
"_id" : ObjectId("5e1757b919c2d113022f4586"),
"adminUserId" : "3",
"userName" : "Mark",
"position" : "Lead",
"departmentUserinfo" : {
"_id" : ObjectId("5e1757f219c2d113022f4589"),
"userId" : "3",
"userName" : "Mark",
"position" : "Lead",
"adminUserId" : "3"
}
}
Upvotes: 1