2016-04-25 13:18
浏览 46

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!


图片转代码服务由CSDN问答提供 功能建议

首先,我不得不说我是mongo(3.2)的新手。 我正在使用 mongo-odm-aggregation-bundle for php framework 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'),

现在,我想通过dateFrom,dateTo和userId限制此查询。 我不确定,怎么做。 我知道,我应该使用匹配功能,但我不知道如何。 或者有更好的解决方案吗?



  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douren6874 2016-04-25 15:03

    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') ])
    点赞 评论
  • douzi2778 2016-05-11 11:46

    In my case, match() was somewhat tricky on a MongoId object.

    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.

    点赞 评论

相关推荐 更多相似问题