用于过滤掉mongodb中引用的($ ref)数组对象的$ elemMatch不起作用

昂斯曼

我有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"
}


ΝΝιΓΞΗΛψΚ

在查询中使用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"
        }
    ]
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章