Bạn có thể thử,
-
$addFieldsđể tạo một mảng duy nhất được gọi làuserIdstạo thành cả hai mảngfollowersvàfollowings,$setUnionđể nhận các id duy nhất, -
$lookupvới bộ sưu tập của người dùng -
$projectđể hiển thị các trường,-
followerslấy fullName, $ map để lặp lại vòng lặp củafollowersvà lấy tên củafollowerIdtừ mảng người dùng bằng cách sử dụng$reducevà$cond -
followingslấy fullName, $ map để lặp lại vòng lặp củafollowingsvà lấy tên củafollowingIdtừ mảng người dùng bằng cách sử dụng$reducevà$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"
]
}
}
}
}
]
}
}
}
}
}
])