问题
I don't understand what I'm missing with the aggregation lookup using join conditions and uncorrelated sub-queries.
processes
collection:
{
_id: 'p1',
steps: [
{
_id: 'ps1',
step: 's1',
time: 10
},
{
_id: 'ps2',
step: 's2',
time: 15
}
]
}
steps
collection (for the document with _id: s1
):
{
_id: 's1',
name: 'step 1'
}
Working aggregation (standard one, without join conditions and uncorrelated sub-queries):
processes.aggregate([
{
// match stage or whatever prior stage
},
{
$lookup: {
from: 'steps',
localField: 'steps.step',
foreignField: '_id',
as: 'steps'
}
}
])
Output:
{
_id: 'p1',
steps: [
{
_id: 's1',
name: 'step 1'
},
{
_id: 's2',
name: 'step 2'
}
]
}
Not working aggregation:
processes.aggregate([
{
// match stage or whatever prior stage
},
{
$lookup: {
from: 'steps',
let: { stepId: '$steps.step' }, // I think the problem is here
pipeline: [
{
$match: {
$expr: { $eq: ['$_id', '$$stepId'] },
},
},
{
// Additional stages here
}
],
as: 'steps',
},
}
])
Output:
{
_id: 'p1',
steps: []
}
回答1:
steps.step
evaluates to an array of strings in this case ["s1", "s2"]
. The regular $lookup
supports such comparison and does $in
behind the scenes.
In your second example you're using $expr
so you need to use expression language hence you have to use $in operator:
$expr: { $in: ['$_id', '$$stepId'] }
Mongo Playground
来源:https://stackoverflow.com/questions/62327702/mongodb-lookup-array-of-objects-by-field-join-conditions-and-uncorrelated-sub-q