简体   繁体   English

Symfony mongo-odm-aggregation-bundle sums

[英]Symfony mongo-odm-aggregation-bundle sums

For start, I have to say I am new to mongo (3.2). 首先,我不得不说我是mongo(3.2)的新手。 I am using mongo-odm-aggregation-bundle for php framework Symfony (2.8.4). 我正在使用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. 现在,我想通过dateFrom,dateTo和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! 谢谢你的回复!

KP KP

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

In my case, match() was somewhat tricky on a MongoId object. 在我的例子中,match()在MongoId对象上有点棘手。

This didn't work for me: 这不适合我:

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

This worked: 这有效:

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

Tested on Symfony 3 with the SolutionMongoAggregationBundle, MongoDB version 3.2.6. 使用SolutionMongoAggregationBundle,MongoDB版本3.2.6在Symfony 3上测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM