首页 > 解决方案 > Mongo $addToSet 一个数组

问题描述

我有一个工作查询:

$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'。

标签: phpmongodbaggregation-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'=>'$current_offense_literal', 'current_offense_literal_value' =>'$current_offense_literal_value']]]

                    ]
                ]);

            });

推荐阅读