MongoDB lookup array of objects by field (join conditions and uncorrelated sub-queries)

岁酱吖の 提交于 2020-06-28 03:56:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!