user1936720 user1936720 - 1 year ago 289
PHP Question

Symfony mongo-odm-aggregation-bundle sums

For start, I have to say I am new to mongo (3.2). I am using mongo-odm-aggregation-bundle for php framework Symfony (2.8.4). I want to get sums of some fields restricted by dates.
So far, I managed to get sums for all records:

$expr = new \Solution\MongoAggregation\Pipeline\Operators\Expr;
$aq = $this->manager->getCollection('AppBundle:UserDaySums')->createAggregateQuery()->group([
'_id' => 'client.$id',
'total' => $expr->sum('$aSum'),

Now, I'd like to restrict this query by dateFrom,dateTo and userId. I am not sure, how to do it. I know, I should probably use match function, but I don't know how. Or is there some better solution?

Thanks for replies!


Answer Source

Yes, you can use the match function. For example, the following assumes you have the date variables for use in the query:

$expr = new \Solution\MongoAggregation\Pipeline\Operators\Expr;
$aq = $this->manager->getCollection('AppBundle:UserDaySums')->createAggregateQuery();
$dateFrom = new MongoDate(strtotime('-2 days'));
$dateTo = new MongoDate();
$userId = 'Xsgy62js0lb';

$result = $aq->match(['dateFrom'=>$dateFrom, 'dateTo'=>$dateTo, 'userId'=>$userId ])
             ->group(['_id'=>'client.$id', 'total'=>$expr->sum('$aSum') ])