Symfony mongo-odm-aggregation-bundle sums


Symfony mongo-odm-aggregation-bundle sums

首先,我不得不说我是mongo(3.2)的新手。我正在使用mongo-odm-aggregation-bundle用于php框架Symfony(2.8.4)。我想获取受日期限制的某些字段的总和。到目前为止,我设法获得了所有记录的总和:

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

现在,我想按日期开始,日期到和用户ID来限制此查询。我不确定,该怎么做。我知道,我可能应该使用匹配功能,但我不知道怎么做。还是有更好的解决方案?

感谢您的回复!

金伯利进程

是的,您可以使用匹配功能。例如,以下假设您具有要在查询中使用的日期变量:

$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') ])
             ->getQuery()->aggregate();

就我而言,match() 在 MongoId 对象上有点棘手。

这对我不起作用:

$userMongoId = "57321c7a2977f8de306ef648";
$aq ->match([ 'user.$id' => $expr->eq($userMongoId) ])

这奏效了:

$aq ->match([ 'user' => new 'MongoId($userMongoId) ])

在Symfony 3上使用SolutionMongoAggregationBundle,MongoDB版本3.2.6进行测试。