Extension of this Question, accepted answer is working but there are some things which i am not understanding.
Everything is working but there is one more thing in this is if array1 i.e shiftListData
does not have any data of any date for example lets take 25th Jan 2023
but array2 i.e attendances
have data of 25th Jan 2023
then it will not merge both object and return nothing i.e it will skip that date even if data is present on array2
From my interpretation, the question is more concerned about "patching" the info from attendances
into shiftListData
. While your concern is correct and understandable, I would say the case may not be that meaningful since it will not create meaningful, merged shiftListData
in this case.
However, the above is just my personal interpretation. We can still solve your question by applying the same idea from the original solution. We just need to revert the merging order to create another merged result. Use $setUnion
to join them together to create the final merged list.
db.collection.aggregate([
{
$set: {
shiftListData1: {
$map: {
input: "$shiftListData",
as: "shift",
in: {
$mergeObjects: [
"$$shift",
{
$ifNull: [
{
$first: {
$filter: {
input: "$attendances",
cond: {
$eq: [
"$$this.Date",
"$$shift.date"
]
}
}
}
},
{}
]
}
]
}
}
},
shiftListData2: {
$map: {
input: "$attendances",
as: "a",
in: {
$mergeObjects: [
{
$ifNull: [
{
$first: {
$filter: {
input: "$shiftListData",
cond: {
$eq: [
"$$this.date",
"$$a.Date"
]
}
}
}
},
{}
]
},
"$$a"
]
}
}
},
attendances: "$$REMOVE"
}
},
{
"$project": {
shiftListData: {
$setUnion: [
"$shiftListData1",
"$shiftListData2"
]
}
}
}
])