我现在在和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
        }
    ]
}我使用以下查询:
db.grades.aggregate([
    { $match: { student_id: 0 } },
    { 
        $redact: {
            $cond: {
                if: { $eq: [ "$type" , "exam" ] },
                then: "$$PRUNE",
                else: "$$DESCEND"
            }
        }
    }] );
使用此查询,可以找到每个类型的考试,应排除该子文档。它起作用了,结果是:
{
    "_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
    }
]
}但如果我把情况颠倒过来,我希望结果中只保留考试:
if: { $eq: [ "$type" , "exam" ] },
       then: "$$DESCEND",
       else: "$$PRUNE" 然而,结果是空的。
我不明白为什么不包括“考试”类型的子文件。
发布于 2015-09-18 14:05:25
$redact阶段从根文档及其字段开始,只有当该文档满足$$DESCEND的条件时,它才检查包含在该文档中的子文档。这意味着$redact对您的文档所做的第一件事是检查以下内容:
{
    "_id" : ObjectId("50b59cd75bed76f46522c34e"),
    "student_id" : 0,
    "class_id" : 2,
    "scores" : [] // Some array. I will look at this later.
}这里甚至没有找到一个type字段,所以$eq: [ "$type" , "exam" ]是假的。当条件为false时,您让$redact做什么?else: "$$PRUNE",所以在检查子文档之前,会对整个文档进行修剪。
作为解决办法,测试$type是"exam"还是不存在。您并没有明确地要求一个有效的解决方案,所以我将把它作为一个练习,让您来研究如何做到这一点。
https://stackoverflow.com/questions/32653442
复制相似问题