試すことができます
-
$addFieldsuserIdsという一意の配列を作成します 両方の配列を形成するfollowersおよびfollowings、$setUnion一意のIDを取得するには -
$lookupユーザーコレクション付き -
$projectフィールドを表示するには、followersfullName、$ mapを取得して、followersのループを繰り返しますfollowerIdの名前を取得します$reduceを使用してユーザー配列から および$condfollowingsfullName、$ mapを取得して、followingsのループを繰り返しますfollowingIdの名前を取得します$reduceを使用してユーザー配列から および$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"
]
}
}
}
}
]
}
}
}
}
}
])