[英]Mongodb aggregation framework and nested $lookup
I'm trying to do a nested population by using the mongodb's aggregation framework and I have some troubles with it. 我试图通过使用mongodb的聚合框架来进行嵌套填充,我遇到了一些麻烦。
This is the initial data that I have: 这是我的初始数据:
[
{
_id: ObjectId('123'),
profileId: ObjectId('456')
},
// ...other documents
]
I apply this aggregation pipeline to it so I can populate the profile
field by using the profileId
field: 我将此聚合管道应用于它,以便我可以使用profileId
字段填充profile
字段:
MyModel.aggregate([
{
$lookup: {
from: 'profiles',
localField: 'profileId',
foreignField: '_id',
as: 'profile'
}
},
{
$project: {
profile: {
$arrayElemAt: [ '$profile', 0 ]
},
profileId: 1,
}
},
]
And this is the result: 这就是结果:
[
{
_id: ObjectId('123'),
profileId: ObjectId('456'),
profile: {
grades: [
ObjectId('...'),
ObjectId('...')
]
// ... other props
}
}
// ...other documents
]
Now I expand the pipeline by adding a $lookup
to populate the grades inside each profile
document: 现在我通过添加$lookup
来扩展管道,以填充每个profile
文件中的成绩:
MyModel.aggregate([
{
$lookup: {
from: 'profiles',
localField: 'profileId',
foreignField: '_id',
as: 'profile'
}
},
{
$project: {
profile: {
$arrayElemAt: [ '$profile', 0 ]
},
profileId: 1,
}
},
{
$lookup: {
from: 'profile-grades',
localField: 'profile._id',
foreignField: 'profile',
as: 'profile.grades'
}
}
]
This is the result so far: 这是迄今为止的结果:
[
{
_id: ObjectId('123'),
profileId: ObjectId('456'),
profile: {
grades: [
{
studyLocationId: ObjectId('789'),
// ... other props
},
// ... other grades
]
}
}
// ...other documents
]
The final step that I'm not able to achieve is the population of each studyLocation
inside the grades
array. 我无法实现的最后一步是grades
数组中每个studyLocation
的数量。
Wanted result: 通缉结果:
[
{
_id: ObjectId('123'),
profileId: ObjectId('456'),
profile: {
grades: [
{
studyLocationId: ObjectId('789'),
studyLocation: {
_id: ObjectId('...'),
// other props
},
},
// ... other grades
]
}
}
// ...
]
I've tried by adding another $lookup
stage but without luck: 我试过添加另一个$lookup
阶段,但没有运气:
{
$lookup: {
from: 'study-locations',
localField: 'profile.grades.studyLocationId',
foreignField: '_id',
as: 'profile.grades.studyLocation'
}
}
This simply returns: 这简单地返回:
grades: {
studyLocation: []
}
How should I do it? 我该怎么办? Is this even possible? 这甚至可能吗? Thank you! 谢谢!
如果您使用的是mongodb3.4,这将有效,对于以前的版本,您需要在成绩上展开运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.