Mongo $ addTo设置一个数组

时间:2018-12-10 15:02:07

标签: php mongodb aggregation-framework

我有一个有效的查询:

$offenses = \App\LawCase::raw(function ($collection)  {
                return $collection->aggregate([
                    [
                        '$match' => ['active' => true, 'type' => 'criminal', 'current_offense_literal'=> ['$exists' => true]]
                    ],
                    [
                        '$group' => ['_id' => '$current_offense_category', 'offense_literals' => ['$addToSet' => '$current_offense_literal']]

                    ]
                ]);

            });

我只想向上面的addToSet添加一个附加值。例如,每个current_offense_literal都有一个current_offense_literal_value,我想将其与current_offense_literal一起添加。

我尝试过的事情:

$offenses = \App\LawCase::raw(function ($collection)  {
                return $collection->aggregate([
                    [
                        '$match' => ['active' => true, 'type' => 'criminal', 'current_offense_literal'=> ['$exists' => true]]
                    ],
                    [
                        '$group' => ['_id' => '$current_offense_category', 'offense_literals' => ['$addToSet' => ['$current_offense_literal'=>['$push'=> '$current_offense_literal_value']]]]

                    ]
                ]);

            });

但是我得到: 无法识别的表达式'$ current_offense_literal'。

1 个答案:

答案 0 :(得分:1)

尝试这样做,

$offenses = \App\LawCase::raw(function ($collection)  {
                return $collection->aggregate([
                    [
                        '$match' => ['active' => true, 'type' => 'criminal', 'current_offense_literal'=> ['$exists' => true]]
                    ],
                    [
                        '$group' => ['_id' => '$current_offense_category', 'offense_literals' => ['$addToSet' => ['current_offense_literal'=>'$current_offense_literal', 'current_offense_literal_value' =>'$current_offense_literal_value']]]

                    ]
                ]);

            });