How To Lookup A Field With An Array In Nested Subdocument Mongodb?
I am trying to retrieve some lookup data for an embedded array in a document. Here is a sample of the data: { '_id': '58a4fa0e24180825b05e14e9', 'fullname': 'Test User'
Solution 1:
You can use lookup pipeline to handle nested lookup
const pipeline = [
{
$match: {_id: new mongoose.Types.ObjectId(req.user.userId)}
},
{
$lookup: {
from: 'levels',
let: { level_id: "$teamInfo.challenges.levelId" },
pipeline: [
{
$match: {
$expr: {
$eq: ["$_id", "$$level_id"]
}
}
},
{
$lookup: {
from: '<level collection>',
localField: "levelId",
foreignField: "_id",
as: "levelInfo"
}
},
{
$project: {
levelInfo: {
name: "$levelInfo.name"
}
title: 1
}
}
],
as: "challenges"
},
},
{ $project: {
_id: 1,
fullname: 1,
username: 1,
teamInfo: {
challenges: "$challenges"
}
}}
]
const result = await User.Aggregate(pipeline)
hope this help !
Post a Comment for "How To Lookup A Field With An Array In Nested Subdocument Mongodb?"