mongodb中的Redact似乎对我来说很模糊

Hug*_*ège 6 mongodb aggregation-framework

我现在正在与redact斗争,我不确定理解它.

我只是阅读了文档并试图在集合等级上使用redact(它来自mongodb在线培训)

集合"成绩"中的文档如下所示:

{
    "_id" : ObjectId("50b59cd75bed76f46522c34e"),
    "student_id" : 0,
    "class_id" : 2,
    "scores" : [ 
        {
            "type" : "exam",
            "score" : 57.92947112575566
        }, 
        {
            "type" : "quiz",
            "score" : 21.24542588206755
        }, 
        {
            "type" : "homework",
            "score" : 68.19567810587429
        }, 
        {
            "type" : "homework",
            "score" : 67.95019716560351
        }, 
        {
            "type" : "homework",
            "score" : 18.81037253352722
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我使用以下查询:

db.grades.aggregate([
    { $match: { student_id: 0 } },
    { 
        $redact: {
            $cond: {
                if: { $eq: [ "$type" , "exam" ] },
                then: "$$PRUNE",
                else: "$$DESCEND"
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

]);

通过此查询,找到每种类型的检查,应排除此子文档.它的工作原理是:

{
    "_id" : ObjectId("50b59cd75bed76f46522c34e"),
    "student_id" : 0,
    "class_id" : 2,
    "scores" : [ 
    {
        "type" : "quiz",
        "score" : 21.24542588206755
    }, 
    {
        "type" : "homework",
        "score" : 68.19567810587429
    }, 
    {
        "type" : "homework",
        "score" : 67.95019716560351
    }, 
    {
        "type" : "homework",
        "score" : 18.81037253352722
    }
]
}
Run Code Online (Sandbox Code Playgroud)

但如果我改变了条件,我希望结果中只保留考试:

if: { $eq: [ "$type" , "exam" ] },
       then: "$$DESCEND",
       else: "$$PRUNE" 
Run Code Online (Sandbox Code Playgroud)

但结果是空的.

我不明白为什么不包括"考试"类型的子文档.

Phi*_*ipp 9

$redact阶段始于根文件及其字段,只有当文件满足条件$$DESCEND,它包括检查该文件中的子文件.这意味着$ redact对你的文档做的第一件事就是检查:

{
    "_id" : ObjectId("50b59cd75bed76f46522c34e"),
    "student_id" : 0,
    "class_id" : 2,
    "scores" : [] // Some array. I will look at this later.
}
Run Code Online (Sandbox Code Playgroud)

它甚至没有type在这里找到一个字段,所以$eq: [ "$type" , "exam" ]是错误的.当条件为假时,你告诉$ redact做了什么?else: "$$PRUNE",因此在检查子文件之前整理整个文件.

作为一种变通方法,测试,如果$type是两种"exam"或者不存在.你没有明确要求一个有效的解决方案,所以我会把它作为练习让你弄清楚如何做到这一点.