MongoDB 将数组与嵌套文档中的值进行匹配

问题描述 投票:0回答:1

我已经围绕我面临的这个问题进行了一些搜索,但在不使用 $lookup 参数的情况下我还没有找到一个好的解决方案。

我的文档目前大致如下所示:

{
    ...
    problems:
        [ { ... id: 1, ...}, { ... id: 7, ...}, { ... id: 122, ...} ],
    solutions:
        [ { ... assignedProblems: [1, 7] ... }, { ... assignedProblems: [122] ...} ],
    ... 
}

我现在正在尝试将

assignedProblems
数组与
id
中的
problems
进行匹配。

我当前的聚合如下所示:

{
    $unwind: {
        path: "$solutions"
    },
    $lookup: {
        from: "problems",
        localField: "solutions.assignedProblems",
        foreignField: "id",
        as: "problems"
    }
}

即使使用索引,这种聚合工作也完美无缺,但速度却非常慢。

我尝试用以下内容替换 $lookup:

    $match: {
        $expr: {
            $setEquals: ["$solutions.assignedProblems", "$problems.id"]
        }
     }

但这仅在问题数量与signedProblems 数组中的元素相同时才有效。这与使用 $eq 运算符时的情况相同。

还有其他方法可以将这些 id 与数组匹配吗?

arrays database mongodb mongodb-query
1个回答
0
投票

我已经找到了我想做的事情的解决方案。

我将

$lookup
阶段替换为这个阶段:

$addFields: {
    problems: {
        $filter: {
            input: "$problems",
            cond: {
                $in: ["$$this.id", "$solutions.assignedProblems"]
            }
        }
    }
}

这会将问题数组替换为一个新数组,该数组仅包含

problems
数组中具有 id 元素的
assignedProblems
对象。

© www.soinside.com 2019 - 2024. All rights reserved.