本文介绍了MongoDB按字段查找对象的数组(联接条件和不相关的子查询)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不了解使用连接条件和不相关子查询.

处理集合:

{
    _id: 'p1',
    steps: [
        {
            _id: 'ps1',
            step: 's1',
            time: 10
        },
        {
            _id: 'ps2',
            step: 's2',
            time: 15
        }
    ]
}

steps 集合(对于具有 _id:s1 的文档):

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'
        }
    }
])

输出:

{
    _id: 'p1',
    steps: [
        {
            _id: 's1',
            name: 'step 1'
        },
        {
            _id: 's2',
            name: 'step 2'
        }
    ]
}

不起作用的聚合:

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',
        },
    }
])

输出:

{
    _id: 'p1',
    steps: []
}

推荐答案

steps.step 在这种情况下计算为字符串数组 ["s1","s2"] .常规的 $ lookup 支持这种比较,并且在后台进行 $ in .

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.

在第二个示例中,您使用的是 $ expr ,因此您需要使用表达式语言,因此必须使用 $ in 运算符:

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'] }

蒙戈游乐场

这篇关于MongoDB按字段查找对象的数组(联接条件和不相关的子查询)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 08:51