根据我的解释,问题更关心的是将信息从attendances“修补”到shiftListData。虽然您的担忧是正确且可以理解的,但我想说这种情况可能没有那么有意义,因为在这种情况下它不会产生有意义的合并shiftListData。
不过,以上只是我个人的解读。我们仍然可以通过应用与原始解决方案相同的想法来解决您的问题。我们只需要恢复合并顺序来创建另一个合并结果。使用 $setUnion 将它们连接在一起以创建最终的合并列表。
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"
]
}
}
}
])
Mongo Playground