Je kunt het proberen,
$addFields
om een unieke array te maken met de naamuserIds
vorm beide arraysfollowers
enfollowings
,$setUnion
om unieke id's te krijgen,$lookup
met gebruikersverzameling$project
om velden te tonen,followers
krijg fullName, $map om de lus vanfollowers
te herhalen en krijg de naam vanfollowerId
van gebruikersarray met behulp van$reduce
en$cond
followings
krijg fullName, $map om de lus vanfollowings
te herhalen en krijg de naam vanfollowingId
van gebruikersarray met behulp van$reduce
en$cond
db.followings.aggregate([
{
$addFields: {
userIds: {
$setUnion: [
{
$map: {
input: "$followers",
in: "$$this.followerId"
}
},
{
$map: {
input: "$followings",
in: "$$this.followingId"
}
}
]
}
}
},
{
$lookup: {
from: "users",
localField: "userIds",
foreignField: "_id",
as: "users"
}
},
{
$project: {
userId: 1,
followers: {
$map: {
input: "$followers",
as: "f",
in: {
$mergeObjects: [
"$$f",
{
fullName: {
$reduce: {
input: "$users",
initialValue: "",
in: {
$cond: [
{ $eq: ["$$this._id", "$$f.followerId"] },
"$$this.fullName",
"$$value"
]
}
}
}
}
]
}
}
},
followings: {
$map: {
input: "$followings",
as: "f",
in: {
$mergeObjects: [
"$$f",
{
fullName: {
$reduce: {
input: "$users",
initialValue: "",
in: {
$cond: [
{ $eq: ["$$this._id", "$$f.followingId"] },
"$$this.fullName",
"$$value"
]
}
}
}
}
]
}
}
}
}
}
])