kratos
kratos

Reputation: 2495

Mongo $addToSet an Array

I have a working query:

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

                    ]
                ]);

            });

I just want to add an additional value to the addToSet above. For example Each current_offense_literal also has a current_offense_literal_value and I would like to add that along with current_offense_literal.

What i tried:

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

                    ]
                ]);

            });

But I am getting: Unrecognized expression '$current_offense_literal'.

Upvotes: 0

Views: 847

Answers (1)

gokultp
gokultp

Reputation: 165

try doing this,

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

                    ]
                ]);

            });

Upvotes: 1

Related Questions