MongoDB聚合:查找数组子级的对象

时间:2020-02-07 11:39:04

标签: mongodb aggregation-framework

我有以下格式的记录集。

学生

[
    {
        "name" : "student A",
        "type" : 1,
        "results" : [ 
            {
                "position" : 1,
                "percent" : 90,
                "test_id" : ObjectId("aaaa")
            }, 
            {
                "position" : 2,
                "percent" : 88,
                "test_id" : ObjectId("bbbb")
            }
        ]
    },
    {
        "name" : "student B",
        "type" : 1,
        "results" : [
            {
                "position" : 2,
                "percent" : 56,
                "test_id" : ObjectId("bbbb")
            }
        ]
    }
]

测试

{
    "_id" : ObjectId("aaaa"),
    "name" : "Test A",
},
{
    "_id" : ObjectId("bbbb"),
    "name" : "Test B",
}

这是我的必需输出,条件: Test.name =“ Test A”

[
    {
        "name" : "student A",
        "type" : 1,
        "results" : [ 
            {
                "position" : 1,
                "percent" : 90,
                "test" : {
                    "_id" : ObjectId("aaaa"),
                    "name" : "Test A",
                }
            }, 
            {
                "position" : 2,
                "percent" : 88,
                "test" : {
                    "_id" : ObjectId("bbbb"),
                    "name" : "Test B",
                }
            }
        ]
    }
]

我尝试了汇总,展开和项目的各种组合,但仍然不能完全达到目标,真的很感谢任何建议。

1 个答案:

答案 0 :(得分:1)

此管道应为您工作:

[{
    $match: {
        name: "student A"
    }
}, {
    $unwind: {
        path: "$results"
    }
}, {
    $lookup: {
        from: 'TEST',
        localField: 'results.test_id',
        foreignField: '_id',
        as: 'results.test'
    }
}, {
    $group: {
        _id: "$name",
        name: {
            $first: "$name"
        },
        type: {
            $first: "$type"
        },
        results: {
            $push: "$results"
        }

    }
}]

以下是管道的屏幕截图,因此您可以查看每个阶段发生的情况: pipeline part 1 pipeline part 2

如果要摆脱多余的字段,可以添加一个项目阶段。