首页 > 解决方案 > $elemMatch 用于过滤 mongodb 中的引用($ref)数组对象不起作用

问题描述

我有 2 个集合 student_details 和 subject_details,每个学生可以有多个科目,我将这些科目存储在 student_details 集合中作为参考数组。

现在我需要获取学生详细信息以及经过过滤的主题,其中 subject_details.status=ACTIVE。

我如何使用对象来实现这$elemMatch一点$ref。我正在使用类似下面的东西,但它没有返回任何记录。

db.getCollection('student_details').find( { subjects: { $elemMatch: { $ref: "subject_details", status: 'ACTIVE' }}})

student_details
================
{
    "_id" : "STD-1",
    "name" : "XYZ",
    "subjects" : [ 
        {
            "$ref" : "subject_details",
            "$id" : "SUB-1"
        },
        {
            "$ref" : "subject_details",
            "$id" : "SUB-2"
        },
        {
            "$ref" : "subject_details",
            "$id" : "SUB-3"
        }
    ]
}

subject_details
===============
{
    "_id" : "SUB-1",
    "name" : "MATHEMATICS",
    "status" : "ACTIVE"
}

{
    "_id" : "SUB-2",
    "name" : "PHYSICS",
    "status" : "ACTIVE"
}

{
    "_id" : "SUB-3",
    "name" : "CHEMISTRY",
    "status" : "INACTIVE"
}


标签: mongodbspring-bootmongodb-queryspring-dataspring-data-mongodb

解决方案


dbref 在查找中使用时很麻烦。但您可以使用以下聚合管道解决它:

db.student_details.aggregate([
    {
        $unwind: "$subjects"
    },
    {
        $set: {
            "fk": {
                $arrayElemAt: [{
                    $objectToArray: "$subjects"
                }, 1]
            }
        }
    },
    {
        $lookup: {
            "from": "subject_details",
            "localField": "fk.v",
            "foreignField": "_id",
            "as": "subject"
        }
    },
    {
        $match: {
            "subject.status": "ACTIVE"
        }
    },
    {
        $group: {
            "_id": "$_id",
            "name": {
                $first: "$name"
            },
            "subjects": {
                $push: {
                    $arrayElemAt: ["$subject", 0]
                }
            }
        }
    }
])

生成的对象将是这样的:

{
    "_id": "STD-1",
    "name": "XYZ",
    "subjects": [
        {
            "_id": "SUB-1",
            "name": "MATHEMATICS",
            "status": "ACTIVE"
        },
        {
            "_id": "SUB-2",
            "name": "PHYSICS",
            "status": "ACTIVE"
        }
    ]
}

推荐阅读