更新嵌套数组MongoDB和laravel中的对象

时间:2018-03-19 11:32:02

标签: mongodb laravel jenssegers-mongodb

我正在尝试更新另一个数组(嵌套数组)中存在的数组中的单个对象,但是会删除所有记录并插入新记录 这是我正在使用的结构:

"summary_mark" : [
    {
        "target_id" : "5aa27e77967c552b10ea725b", 
        "primitives" : [
            {
                "primitive" : "B", 
                "test_count" : NumberInt(3), 
                "right_test_count" : NumberInt(3), 
                "mark" : NumberInt(66)
            }, 
            {
                "primitive" : "T", 
                "test_count" : NumberInt(3), 
                "right_test_count" : NumberInt(3), 
                "mark" : NumberInt(66)
            }, 
            {
                "primitive" : "H", 
                "test_count" : NumberInt(3), 
                "right_test_count" : NumberInt(3), 
                "mark" : NumberInt(66)
            }
        ]
    }
], 

我要做的是更改基元数组中的一条记录。

实际上我正在尝试使用此功能更新记录:

$testCount = ++$primitiveSummaryMark['test_count'];
        $update['summary_mark.$.primitives'][$primKey]['primitive'] = $answer->primitive_value;
        $update['summary_mark.$.primitives'][$primKey]['test_count'] = $testCount;

        if ($answer->result != 0) {
            $rightAnswersCount = ++$primitiveSummaryMark['right_test_count'];
            $update['summary_mark.$.primitives'][$primKey]['right_test_count'] = $rightAnswersCount;
        } else {
            $rightAnswersCount = $primitiveSummaryMark['right_test_count'];
        }

        if ($testCount < $level_tests_amount->tests_count[$target_level]) {
            $totalTestCount = $level_tests_amount->tests_count[$target_level];
        } else {
            $totalTestCount = $testCount;
        }

        $primitiveTargetMark = ($rightAnswersCount * 100) / $totalTestCount;
        $update['summary_mark.$.primitives'][$primKey]['mark'] = $primitiveTargetMark;

我执行某些逻辑然后运行此查询:

MyClass::raw()
        ->findOneAndUpdate([
            'course' => $this->first()->course,
            'summary_mark.target_id' => $data->target_id,
        ],
            ['$set' => $update]);

输入是这样的:

{"data":{ "target_id":"5aa27e77967c552b10ea725b","question":"5aa141b6c8af28381079e9c7", "answers":[{"primitive_value":"B","result":1,"elpassed_time":20,"distructor":""},{"primitive_value":"T","result":1,"elpassed_time":3,"distructor":""}]}}

我期望看到的是具有基元(B,T,H)的记录,但是我得到(B,T)导致它们因输入而被更新的那些

0 个答案:

没有答案