我正在将mongo查询转换为symfony4学说ODM查询。在这种情况下,学说将不接受多个分组依据字段。如何解决以下用例?
Mongo查询:
db.Article.aggregate([
{
$group: {
_id: { department: "$department", status : "$status" },
MIN: { $min: "$salary" },
MAX: { $max: "$salary" }
}
}
]);
Mongo查询结果:
{ "_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与教义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);
仅按部门领域考虑。我想按部门和基于状态的分组结果分组。
答案 0 :(得分:1)
此解决方案适用于Symfony3。在ArticleRepository.php文件中,编写以下行:
$qb = $this->createAggregationBuilder('Document\Article');
$group_expression = $qb->expr()
->field('departement')
->expression('$department')
->field('max')
->expression('$max')
->field('min')
->expression('$min');
$qbf->group()
->field('id')
->expression($group_expression)
->field('department')
->first('$department')
->field('status')
->first('$status')
->field('lowestValue')
->min('$salary')
->field('highestValue')
->max('$salary')
->field('totalValue')
->sum(1);