Mongodb-odm: symfony4 with doctrine-odm : How to add one or more group in aggregation builder

Created on 25 Jan 2019  路  2Comments  路  Source: doctrine/mongodb-odm

I am converting mongo queries into symfony4 doctrine odm queries. In this, doctrine will not accept the multiple group by fields. How to solve the below use case?

Mongo Queries:


db.Article.aggregate([
    {
        $group: {
            _id: { department: "$department", status : "$status" },
            MIN: { $min: "$salary" },
            MAX: { $max: "$salary" }
        }
    }
]);

Mongo Query Results:


{ "_id" : { "department" : "sales", "status" : 0 }, "MIN" : 100, "MAX" : 5000 }
{ "_id" : { "department" : "sales", "status" : 1 }, "MIN" : 10000, "MAX" : 16500 }
{ "_id" : { "department" : "IT", "status" : 1 }, "MIN" : 5000, "MAX" : 5000 }
{ "_id" : { "department" : "DOCTOR", "status" : 1 }, "MIN" : 20000000, "MAX" : 20000000 }
{ "_id" : { "department" : "IAS", "status" : 1 }, "MIN" : 120000, "MAX" : 120000 }

Symfony4 with doctrine odm :


$qb = $this->createAggregationBuilder($documentClass);
$qb
    ->group()
        ->field('id')
        ->expression('$department')
        ->field('department')
        ->first('$department')
        ->field('status')
        ->first('$status')
        ->field('lowestValue')
        ->min('$salary')
        ->field('highestValue')
        ->max('$salary')
        ->field('totalValue')
        ->sum(1);

It will only considered group by field of department alone. I want to group by both department and status based group results. Is this possible?

Question

Most helpful comment

To use a complex identifier, you have to pass it to the identifier using expression:

$builder
    ->group()
    ->field('_id')
    ->expression(
        $builder->expr()
            ->field('department')
            ->expression('$department')
            ->field('status')
            ->expression('$status')
    )
    ->field('lowestValue')
    ->min('$salary')
    // ...
;

All 2 comments

To use a complex identifier, you have to pass it to the identifier using expression:

$builder
    ->group()
    ->field('_id')
    ->expression(
        $builder->expr()
            ->field('department')
            ->expression('$department')
            ->field('status')
            ->expression('$status')
    )
    ->field('lowestValue')
    ->min('$salary')
    // ...
;

@alcaeus Perfectly working...! thanks for your time.

Was this page helpful?
0 / 5 - 0 ratings